Why Type casting???

Hi everybody,

I am new to C++ and I have serious doubts over typecasting....
Why do we typecast in first place?....it makes sesne if we have to typecast among built in data types(like float to int or int to float etc.)

but how typecasting from one object to another object...how does it make any sense?
lets say.....I have one class STUDENT with datamembers as student's marks and another class TEACHER and it's data members as subjects he teach.

Now if I type cast student into teacher object.....how their data members are affected?....how does it make sense to typecast objects that belongs different classes with different data members??
I dont understand a bit of this.

Please helppppp...Can you please give me a scenario where typecasting among different objects(Please dont give an example from base to derived or derived to base) is needed and serve a purpose?

Thanks in advance
venkatacplpl wrote:
if I type cast student into teacher object...
You will get a compile-time error, unless you provide conversion yourself.
venkatacplpl wrote:
how their data members are affected?
As you defined conversion routine

venkatacplpl wrote:
Can you please give me a scenario where typecasting among different objects is needed and serve a purpose
Static cast:
In one project I have seen following:
JPGObject x = LoadTexture(OFFSET);
auto tex = static_cast<BMPObject>(x);

dynamic cast: should be avoided if possible, but it is the safe way to cast to the derived class if possible.

const cast: Should be avoided as plague. Used to remove or add const qualifiers

reinterpret cast: casts pointers around. Useful when manipulating binary data:
char buff[[4];
input.read(buff, 4);
uint34_t value = *reinterpret_cast<uint32_t*>(buff);

The less you use casts the better: use of casts often means that ypur program is badly designed.
Last edited on
> Please dont give an example from base to derived or derived to base

But this is one of the main reason to cast (besides low level stuff like MiiNiPaa already showed with reinterpret_cast).

Assume you have a common base class of student and teacher, let's call it person.

Then you might want to build a function accepting a person
(always use references or pointers if you use a base class)
that displays some information depending on the "real" type of the object passed to this function (see "static type vs. dynamic type" if you want to know more).

Then - after determining if the person passed is a student - you may cast it to a student to access the methods/members specific to students.

But in many cases casts can be replaced by virtual functions in a base class, so you might also have a look at them.
I think the reason he asked not to show that kind of example was because he was already overly familiar with it.
Topic archived. No new replies allowed.