(→Virtual Destructors) |
(→Virtual Destructors) |
||
Line 9: | Line 9: | ||
The problem is how to select the correct destructor when an object referenced by a pointer not of its own class is deleted. | The problem is how to select the correct destructor when an object referenced by a pointer not of its own class is deleted. | ||
<cpp> | <cpp> | ||
− | // | + | // FIRST SCENARIO |
class Base { | class Base { | ||
public: | public: | ||
Line 31: | Line 31: | ||
Defining the destructor virtual in <tt>Base</tt> solves the problem and allows the correct destructor to be selected in the previous example. | Defining the destructor virtual in <tt>Base</tt> solves the problem and allows the correct destructor to be selected in the previous example. | ||
<cpp> | <cpp> | ||
− | // | + | // SECOND SCENARIO |
class Base { | class Base { | ||
public: | public: |
Virtual destructors are needed when class hierarchies are used and when polymorphism is used in the program.
The problem is how to select the correct destructor when an object referenced by a pointer not of its own class is deleted. <cpp> // FIRST SCENARIO class Base { public:
~Base() {} virtual void f() {}
};
class Derived : public Base { public:
~Derived() {} void f() {}
};
void main() {
Base *b = new Derived(); a->f(); // ok: calls Derived::f() delete b; // problems: calls Base::~Base()
} </cpp>
Defining the destructor virtual in Base solves the problem and allows the correct destructor to be selected in the previous example. <cpp> // SECOND SCENARIO class Base { public:
virtual ~Base() {} // virtual destructor virtual void f() {}
};
class Derived : public Base { public:
~Derived() {} void f() {}
};
void main() {
Base *b = new Derived(); a->f(); // ok: calls Derived::f() delete b; // ok: calls Derived::~Derived()
} </cpp>