eg:
#include
using namespace std;
class Base1 {
public:
~Base1() { cout << "~Base1()\n"; }
};
class Derived1 : public Base1 {
public:
~Derived1() { cout << "~Derived1()\n"; }
};
class Base2 {
public:
virtual ~Base2() { cout << "~Base2()\n"; }
};
class Derived2 : public Base2 {
public:
~Derived2() { cout << "~Derived2()\n"; }
};
int main() {
Base1* bp = new Derived1; // Upcast
delete bp;
Base2* b2p = new Derived2; // Upcast
delete b2p;
}
The output of the following program is :--
~Base1()
~Derived2()
~Base2()
In this example we can see that after declaring the destructor of class Base2 as virtual when we delete a pointer to class Base2 then first the Derived2() destructor is called first then the base class destructor. So during upcasting this can introduce a memory leak.This is the case that i know which can introduce memory leak in multiple files.(Reference: TICPP Vol1 Bruce Eckel Chapter 15(polymorphism and Virtual functions))
No comments:
Post a Comment