+ 1

A question

#include <iostream> using namespace std; class A{ public: virtual ~A()=0; }; A::~A(){} class B:public A{ }; int main() { A *ptr=new B; return 0; } Why am I not getting any error while implementing the ~A()? Why the output is "No ouput"?

19th Apr 2018, 11:04 PM
Yusuf
Yusuf - avatar
9 Answers
+ 1
ofcourse i will get linker error unless i do some tricks since the compiler will not understand which class i am refering to base or derived? you may ask why destructor is allowed then it is also member function? the reason is that destructors are always called in reverse order of the class derivation, which means derived destructor will be invoked first then base class destructor will be called, and that is why you can't leave the pure virtual destructor in the base without body.
20th Apr 2018, 11:41 AM
Xiirey Xaashi
Xiirey Xaashi - avatar
+ 1
@Xiirey Try to define a function which is pure virtual function in the base class.
20th Apr 2018, 3:29 AM
Yusuf
Yusuf - avatar
+ 1
But I can leave the pure virtual destructor without body: https://code.sololearn.com/cbLrTuP2jFpo/?ref=app
20th Apr 2018, 12:34 PM
Yusuf
Yusuf - avatar
+ 1
I got what you mean. Thank you @Xiirey 👍
20th Apr 2018, 2:03 PM
Yusuf
Yusuf - avatar
+ 1
TĂŒrkçe'yi yeni Ă¶ÄŸreniyorsun heralde. 😀
20th Apr 2018, 2:06 PM
Yusuf
Yusuf - avatar
0
what kind of error you were expecting? in line5 of your class you declare the class destructor as a pure virtual which means the derived classes will allow to override it with the same signature, in line7 you define the destructor in the base class, now: after the first line of the main method if you delete the pointer of A of type B you will not get the problem of memory leak, and that is why you define your base class destructor as virtual.
20th Apr 2018, 12:46 AM
Xiirey Xaashi
Xiirey Xaashi - avatar
0
so you are driving a question from question! Anyways write this A *a =new B(); in the main you will understand what i mean
20th Apr 2018, 1:39 PM
Xiirey Xaashi
Xiirey Xaashi - avatar
0
ben teƟekkĂŒr ederim
20th Apr 2018, 2:04 PM
Xiirey Xaashi
Xiirey Xaashi - avatar
0
yoo ben turkum zaten yandim biraz😆
20th Apr 2018, 2:07 PM
Xiirey Xaashi
Xiirey Xaashi - avatar