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??

Recommended Answers

All 3 Replies

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.

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).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.