3
votes

I'm confused about virtual destructors. I have read many questions and explanations but i still didn't understand that if there is a derived class from base class, do i need to implement its own destructor even it doesn't have any special operations.

The compiler compiles the code below, but would be there any memory leaks or any problems ?

Class Base{
public:
virtual ~Base(){}
};

Class Derived : public Base{
// do i need a special destructor here for Derived ?
}

Base *foo;
foo = new Derived;
delete foo;
2

2 Answers

2
votes

If you don't provide a destructor for Derived, then one gets created automatically. That automatically created destructor overrides the destructor in Base, so it gets called when you delete foo. The automatically created destructor would be equivalent to this:

Class Derived : public Base {
  ~Derived() { } // this is what you get if you don't provide your own.
}

All destructors, whether they are automatically created or not, will automatically call the destructors of all the members of the class and the destructor of the base class. So everything gets cleaned up nicely.

1
votes

No there will be no memory leaks since Derived will get it's implicit virtual destructor.