Virtual destructors
When applying polymorphism, the destructor of the base class must be defined as virtual
. This is compulsory when the derived class introduces new member variables.
The reason for this necessity can be illustrated with the following code:
Polygon *p = new Square();
delete p;
In the last line, one should call the Square
destructor. If you forget to mark the destructor in Polygon as virtual
, that of Polygon
is called instead. If Square
has added new data members, this can lead to a memory leak.
Note: If you add the flag -Wnon-virtual-dtor
at compilation time, the compiler issues a warning if you have forgotten a virtual destructor.