-1

Why Circle destructor is not called?

#include "stdafx.h"
#include <iostream>

class Shape { 
public:
    Shape() { 
        std::cout << "Shape Constructor\n"; 
    };
    ~Shape() { 
        std::cout << "Shape Destructor\n"; 
    };
};

class Circle: public Shape {
public:
    Circle() { 
        std::cout << "Circle Constructor\n"; 
    };
    ~Circle() { 
        std::cout << "Circle Destructor\n"; 
    };
};

int _tmain(int argc, _TCHAR* argv[])
{
    Shape *object;  
    object = new Circle(); 
    delete object;
    return 0;
}

Output:

Shape Constructor
Circle Constructor
Shape Destructor
jsmith
  • 167
  • 9

1 Answers1

-1

By default, inheriting doesn't allow your derived class destructor to call the base class's destructor automatically. But defining the base class's destructor as virtual enables the derived class to call the base class's destructor implicitly before destruction.

D-RAJ
  • 2,907
  • 1
  • 4
  • 20
  • 1
    just a matter of wording, but its the other way around: `delete object` calls the base class destructor only. "doesn't allow your derived class destructor to call the base class's destructor automatically" thats not what happens also with `virtual` – 463035818_is_not_a_number Feb 08 '21 at 13:21
  • 3
    This answer is only partially correct. Without a virtual destructor in the base class, the `delete` expression has undefined behaviour. While it is reasonably common in practice (i.e. is the case with several compilers) that the result is only calling the base class constructor, that is NOT required by the standard. – Peter Feb 08 '21 at 13:36