You cannot call derived member function in the base destructor!
July 25th, 2020
Comments off
Consider the following code …
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
#include <iostream> using namespace std; class Base { public: Base(){ cout << "Base Constructor\n";} virtual ~Base(){ // the derived class is long gone ... This(); cout << "Base Destructor\n";} virtual void This(){ cout << "Base This\n"; } }; class Derived : Base { public: Derived(){ cout << "Derived Constructor\n";} virtual ~Derived(){ cout << "Derived Destructor\n";} void This() override{ cout << "Derived This\n"; } }; int main() { auto base = new Base(); delete base; cout << "-----------------------------\n"; auto derived = new Derived(); delete derived; return 0; } |
In the code you would be forgiven for thinking that the function “This()” would be called from the derived class, but in fact it is called from the base class
1 2 3 4 5 6 7 8 9 10 11 12 |
Base Constructor Base This Base Destructor ----------------------------- Base Contructor Derived Constructor Derived Destructor <--- Derived is now gone ... Base This <--- we are not calling the derived one Base Destructor |
This is because the derived class has been deleted by the time we call the base destructor.
Moral of the story, clean up what you need to cleanup in your derived class, ’cause the base class is not going to do it for you!
Recent Comments