Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

In this non-compliant example, a pointer to the base class Base is used to refer to a Derived object. When b is deleted, undefined behavior results. Typically, the destructor for Base is invoked rather than the destructor for Derived. As a result, the object b refers to is not properly destroyed.

Code Block
bgColor#FFCCCC
langcpp
class Base {
public:
   Base() {
      // Build Base object
   }
   ~Base() {
      // Destroy Base object
   }
};

class Derived : public Base {
public:
   Derived() {
      // Build Derived object
   }
   ~Derived() {
      // Destroy Derived object
   }
};

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

...

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

Code Block
bgColor#ccccff
langcpp
class Base {
public:
   Base() {
      // Build Base object
   }
   virtual ~Base() {
      // Destroy Base object
   }
};

class Derived : public Base {
public:
   Derived() {
      // Build Derived object
   }
   ~Derived() {
      // Destroy Derived object
   }
};

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

...