0

if i want to dereference an object(using delete operator) of DERIVED class which is being referenced using a BASE class reference, which destructor would b called automatically??
BASE class destructor or DERIVED class destructor??

3
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by arkoenig
0

You need to make the destructor in the base class as virtual (otherwise the base class destructor will be called directly). Try this code:

#include <iostream>

class base1 {
  public:
    virtual ~base1() { //notice virtual keyword here
      std::cout << "base1 destructor called!" << std::endl;
    };
};

class derived1 : public base1 {
  public:
    ~derived1() {
      std::cout << "derived1 destructor called!" << std::endl;
    };
};


class base2 {
  public:
    ~base2() { //notice NO virtual keyword here
      std::cout << "base2 destructor called!" << std::endl;
    };
};

class derived2 : public base2 {
  public:
    ~derived2() {
      std::cout << "derived2 destructor called!" << std::endl;
    };
};

int main() {
  base1* b1 = new derived1;
  base2* b2 = new derived2;

  std::cout << "now deleting b1 and then b2..." << std::endl;

  delete b1;
  delete b2;
};

This will output:
now deleting b1 and then b2...
derived1 destructor called!
base1 destructor called!
base2 destructor called!

I think that should answer your question. So, general rule, always make the base class destructor virtual.

1

You need to make the destructor in the base class as virtual (otherwise the base class destructor will be called directly).

A small, pedantic, correction:

You need to make the destructor in the base class virtual, otherwise the effect is undefined (Most implementations call the base-class destructor without first calling the derived-class destructor, thereby leaving the object's memory in a partially-destroyed state).

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.