Get base class pointer from base pointer pointing to derived class | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Get base class pointer from base pointer pointing to derived class

Hi I have a base class pointer pointing to derived class object. Class is polymorphic. Now, I need to have base pointer pointing to base class from above mentioned pointer. How to get that? Used both static and dynamic cast, but none of them works. In other word, I need pb1 or pb2 pointing to base class in attached code. Refer code below: https://code.sololearn.com/cWtQ3LUVUY62/?ref=app

3rd Dec 2023, 5:50 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
4 Answers
+ 2
these lines (33, 36) do not touch the vtable pointer inside the class. they were pointing to the vtable for Derived when the object was created, and they continue to point to this vtable after the the cast. if you don't want that, then don't make display virtual. but if you do want virtual, but need call base::display, then call it explicitly: pb->base::display();
4th Dec 2023, 12:28 AM
MO ELomari
+ 2
in the case of polymorphic classes , <reinterpret_cast> is not the appropriate choice, especially those involving inheritance and virtual functions, is unsafe for several reasons: - polymorphic classes often involve virtual functions, and objects of such classes have a hidden pointer to the virtual table (vtable), <reinterpret_cast> doesn't respect the polymorphic nature of the class and won't adjust the vtable pointer, leading to incorrect behavior if virtual functions are called. - the layout of objects is compiler-dependent and may include padding for alignment or other reasons, <reinterpret_cast> assumes that the layouts of the source and destination types are identical, which might not be true. - <reinterpret_cast> doesn't consider dynamic type information (e.g., provided by <dynamic_cast> or Run-Time Type Information (RTTI) ), so it can't handle polymorphic types correctly. for safe type conversions involving polymorphic classes, prefer using <dynamic_cast> for runtime checks or <static_cast> if you are certain about the types at compile-time. these casts respect the polymorphic nature and provide more safety checks.
4th Dec 2023, 11:07 AM
MO ELomari
+ 1
Thanks...! Below is working fine as suggested by you.. pb->base::display(); However, reinterpret_cast is also not working even though there is no restriction for this type of casting. base* pb3 = reinterpret_cast<base*>(pb); pb3->display();
4th Dec 2023, 8:46 AM
Ketan Lalcheta
Ketan Lalcheta - avatar
+ 1
Thank you MO ELomari
4th Dec 2023, 11:46 AM
Ketan Lalcheta
Ketan Lalcheta - avatar