+ 1

Why cast Super-class objects to derived-class objects?

Whats the purpose of doing this👇 Creating two classes and extending the 1st with the second,what's the purpose of downcasting a super object to a sub class object,does anything change when i try to use that sub class object.. I.e...... Super* super_obj; Sub* sub_obj=dynamic_cast<*super_obj>(); ...........

3rd Dec 2018, 4:39 AM
Mensch
Mensch - avatar
1 Respuesta
+ 3
You may need to do this if the pointer to the Super class was actually holding an object of the Sub class. You can then safely move it to a Sub class pointer using dynamic_cast. In case the conversion fails, you get a nullptr in sub_obj. Secondly your cast is a bit doubtful. I think what you intended was: Sub* sub_obj = dynamic_cast<Sub*>(super_obj); In your code above, the parenthesis were empty, and the cast must be to the type you are going to store the variable in. (otherwise why cast in the first place?)
3rd Dec 2018, 7:59 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar