nagaradderKantesh
nagaradderKantesh

Reputation: 1690

Destructors in inheritance

I have got doubt when I was going through the code below. I.e why the destructor of derived class is not called even when an object of derived class goes out of scope in the code below:

#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;

class ClassA
{
    protected:
        int width, height;
    public:
      void set_values(int x, int y)
      {
        width = x;
        height = y;
      }
      virtual int area()
      {
        return 0;
      }
      ~ClassA()
      {
         cout << "base class destructor called" << endl;
      }
 };

class ClassB : public ClassA
{
      public :
   int area()
   {
     return (width * height);
   }
   ~ClassB()
       {
      cout << "derived class destructor called" << endl;
   }
 };


 int main()
 {
   ClassA *Ptr = NULL;
   ClassB Obj;
   Ptr = &Obj;
   Ptr->set_values(10, 20);
   cout << Ptr->area() << endl;
   delete Ptr;
     return 0;
 }

Upvotes: 0

Views: 154

Answers (2)

Alok Save
Alok Save

Reputation: 206498

You should not call delete on Base class pointer pointing to derived class object unless the base class destructor is virtual else what you get is Undefined Behavior.

The destructor in base class needs to be marked virtual.

virtual ~ClassA(){}

Upvotes: 4

masoud
masoud

Reputation: 56479

Make your destructor virtual in base class. Otherwise, it calls base's destructor.

class ClassA
{
// ...
      virtual ~ClassA()
      {
         cout << "base class destructor called" << endl;
      }
};

Upvotes: 1

Related Questions