You are viewing an old version of this page. View the current version.

Compare with Current View Page History

« Previous Version 5 Next »

Calling the destructor of a derived class in an inheritance hierarchy should invoke the destructors that class and all of its parent classes. However, if the derived class is referenced by a pointer of a type higher up the class hierarchy, then the destructor of the pointer's type will be called rather than the destructor of the class being pointing to. As a result the derived classes destructor will not be called leading to resource mismanagement and possibly unintended program behavior. To ensure the correct destructor is called, destructors should be declared as virtual.

Non-Compliant Code Example

In this example,

class Base { 
public:
  Base() {  }
  ~Base() {  }
  
};

class Derived : public Base { 
public:
  Derived() {  }
  ~Derived() {  }
};


void main() {
  Base* b = new Derived();
  // ... 
  delete b;

Compliant Solution

  • No labels