the concept of virtual destructors
the concept of virtual destructors
What is: ensuring that your derived class objects will be properly destroyed?
To ensure that the correct destructor is called for objects allocated in the free store, you need to employ virtual destructors. The virtual keyword signals to the compiler that the destructor calls through a pointer or a reference parameter should have dynamic binding, and so the destructor will be selected at runtime. That works in spite of the fact that all the destructors have different names--destructors are treated as a special case for this purpose.
Here's a simple example of using a virtual destructor. DerivedA destructor will not be called and DerivedB will.
Code:#include <iostream.h> class BaseA { public: ~BaseA() { cout << "Called ~BaseA()\n"; } }; class DerivedA : public BaseA { public: ~DerivedA() { cout << "Called ~DerivedA()\n"; } }; class BaseB { public: virtual ~BaseB() { cout << "Called ~BaseB()\n"; } }; class DerivedB : public BaseB { public: ~DerivedB() { cout << "Called ~DerivedB()\n"; } }; int main() { BaseA* Ap = new DerivedA; delete Ap; BaseB* Bp = new DerivedB; delete Bp; return 0; }
thnx for the example.Originally posted by Scarlet7
Here's a simple example of using a virtual destructor. DerivedA destructor will not be called and DerivedB will.
Code:#include <iostream.h> class BaseA { public: ~BaseA() { cout << "Called ~BaseA()\n"; } }; class DerivedA : public BaseA { public: ~DerivedA() { cout << "Called ~DerivedA()\n"; } }; class BaseB { public: virtual ~BaseB() { cout << "Called ~BaseB()\n"; } }; class DerivedB : public BaseB { public: ~DerivedB() { cout << "Called ~DerivedB()\n"; } }; int main() { BaseA* Ap = new DerivedA; delete Ap; BaseB* Bp = new DerivedB; delete Bp; return 0; }
can u provide me with a numerical example which
actually specifies memory leak when virtual destructors are
not used
Code:#include <iostream> using namespace std; class BaseA { public: BaseA(int bA) { m_baseA = bA; } ~BaseA() { cout << "Called ~BaseA()\n"; } private: int m_baseA; }; class DerivedA : public BaseA { public: DerivedA(int dA, int bA):BaseA(bA) { m_derivedA = dA; } ~DerivedA() { cout << "Called ~DerivedA()\n"; } private: int m_derivedA; }; int main() { BaseA* Ap = new DerivedA(1, 2); delete Ap; return 0; }