Back to TILs

C++ virtual destructor

Date: 2024-11-03Last modified: 2024-11-03

Table of contents

class Base1 {
public:
  Base1()
  {
    std::cout << "Base1 constructor" << std::endl;
  }
  ~Base1() // here should be virtual
  {
    std::cout << "Base1 destructor" << std::endl;
  }
};
class Base2 {
public:
  Base2()
  {
    std::cout << "Base2 constructor" << std::endl;
  }
  virtual ~Base2()
  {
    std::cout << "Base2 destructor" << std::endl;
  }
};
class Derived1 : public Base1 {
private:
  double mVal;

public:
  explicit Derived1( const double &val ) : mVal( val )
  {
    std::cout << "Derived1 constructor" << std::endl;
  }
  ~Derived1()   // here should be virtual 
  {
    std::cout << "Derived1 destructor" << std::endl;
  }
};
class Derived2 : public Base2 {
private:
  double mVal;

public:
  explicit Derived2( const double &val ) : mVal( val )
  {
    std::cout << "Derived2 constructor" << std::endl;
  }
  ~Derived2()  // here should be virtual 
  {
    std::cout << "Derived2 destructor" << std::endl;
  }
};
  double d{ 1000 };
  {
    Base1 *p1 = new Derived1( d );
    delete p1; // Derived1 desctructor is not called; mVal is not deallocated
  }
  std::cout << "=============" << std::endl;
  {
    Base2 *p2 = new Derived2( d );
    delete p2; // Derived2 and Base2 desctructor are called
  }

Possible output

Base1 constructor
Derived1 constructor
Base1 destructor
=============
Base2 constructor
Derived2 constructor
Derived2 destructor
Base2 destructor

References