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?
> 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.