(→Virtual Destructors) |
|||
(5 intermediate revisions by the same user not shown) | |||
Line 24: | Line 24: | ||
void main() { | void main() { | ||
Base *b = new Derived(); | Base *b = new Derived(); | ||
− | + | b->f(); // ok: calls Derived::f() | |
delete b; // problems: calls Base::~Base() | delete b; // problems: calls Base::~Base() | ||
} | } | ||
</cpp> | </cpp> | ||
− | Defining the destructor virtual in <tt>Base</tt> solves the problem and allows the correct destructor to be selected | + | Defining the destructor virtual in <tt>Base</tt> solves the problem and allows the correct destructor to be selected: |
<cpp> | <cpp> | ||
// SECOND SCENARIO | // SECOND SCENARIO | ||
Line 46: | Line 46: | ||
void main() { | void main() { | ||
Base *b = new Derived(); | Base *b = new Derived(); | ||
− | + | b->f(); // ok: calls Derived::f() | |
delete b; // ok: calls Derived::~Derived() | delete b; // ok: calls Derived::~Derived() | ||
} | } | ||
Line 52: | Line 52: | ||
"Virtual" does not mean a destructor is any less real: it means only that the correct one to call will be determined at run time (i.e., depending on the object being destroyed). | "Virtual" does not mean a destructor is any less real: it means only that the correct one to call will be determined at run time (i.e., depending on the object being destroyed). | ||
+ | |||
+ | [[category:Ensino]] | ||
+ | [[category:PO]] | ||
+ | [[category:PO Exemplos]] | ||
+ | [[category:C++]] |
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(); b->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: <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(); b->f(); // ok: calls Derived::f() delete b; // ok: calls Derived::~Derived()
} </cpp>
"Virtual" does not mean a destructor is any less real: it means only that the correct one to call will be determined at run time (i.e., depending on the object being destroyed).