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

Compare with Current View Page History

« Previous Version 8 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 non-compliant example, a reference to the parent class Base is used to instantiate a Derived object. When b is deleted, the destructor for Base is invoked rather than the destructor for Derived. As a result, the object b refers to will be improperly destroyed.

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

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

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

Compliant Solution

To correct this example, the destructor for Base should be declared virtual. This ensures that the object b refers to will be correctly evaluated at runtime, thus, deleting b will call the destructor for class Derived.

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

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

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