+ 3

Cpp Inheritance

Why output is so, rather than all base class only some of them created, or printed? https://code.sololearn.com/cO58gtRNU6gP/?ref=app

2nd May 2019, 6:55 AM
Ebubekir Türker
Ebubekir Türker - avatar
2 Réponses
+ 4
The reason is that your destructor isn't virtual. When you assign an object of class B to an pointer of class A, no information about the underlying type of the pointer is available. So when delete is supposed to call the destructor, it calls the one associated with the type of the pointer, which is A. So you only see ~A even when you are trying to destroy an object of type B. This is why a virtual destructor is supported in C++. To fix this issue, simply make the destructor of the base class (A in this case) as virtual (Simply add the virtual keyword before the declaration). This will enable the compiler to call appropriate destructors for objects of subclasses assigned to pointers of superclasses when deleted using delete.
2nd May 2019, 7:13 AM
Solo Wanderer 4315
Solo Wanderer 4315 - avatar
+ 4
Kinshuk Vasisht Thank you very much
2nd May 2019, 7:16 AM
Ebubekir Türker
Ebubekir Türker - avatar