virtual destructor in c++ -
virtual destructor in c++ -
in code below, why ~derived()
destructor called automatically?
#include<iostream> using namespace std; class base of operations { public: virtual ~base() { cout << "calling ~base()" << endl; } }; class derived: public base of operations { private: int* m_pnarray; public: derived(int nlength) { m_pnarray = new int[nlength]; } virtual ~derived() { cout << "calling ~derived()" << endl; delete[] m_pnarray; } }; int main() { derived *pderived = new derived(5); base of operations *pbase = pderived; delete pbase; homecoming 0; }
because base of operations class destructor virtual
virtual ~base();
the phone call delete on pointer base of operations class results in virtual phone call destructor , virtual phone call dispatched matching function in derived class. not good, necessary: otherwise behavior undefined.
this crucial derived classes destructor not empty function. non-virtual phone call otherwise result in calling base of operations class destructor, derived resources beingness leaked, etc.
c++ virtual virtual-destructor
Comments
Post a Comment