1

Suppose that I have this code - this code does nothing and I understand that their is a memory leak as the destructor of car is not virtual. However I do not understand why I get a debug assertion for this code. I am using visual studio 2010.

struct car {
    ~car() 
    {std::cout << "Destructor of car";  }
};
struct honda: public car {
     virtual ~honda()
    { std::cout << "Destructor of honda"; }
};

int main()
{
    car *c = new honda();
    delete c;
}

I do not get this assertion if destructor of honda class is not declared virtual. I wanted to know what is the issue with that ?

Rajeshwar
  • 11,179
  • 26
  • 86
  • 158

2 Answers2

2

To make the destructor virtual, you need to declare it as such in the base class:

struct car {
    virtual ~car() {std::cout << "Destructor of car";  }
 // ↑↑↑↑↑↑↑
};

Without this, your code has undefined behaviour.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
0

To make your derived class destructor virtual, you must have your base class destructor virtual as well. See C++ assertion error while deleting object for a detailed explanation.

The reason the assert goes away when the destructor of honda is not virtual is that it becomes well defined. Although, it is recommended to have base class destructor(s) to be virtual to get the destruction calls through the inheritance hierarchy.

Community
  • 1
  • 1
ap-osd
  • 2,624
  • 16
  • 16