3

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;
j0k
  • 21,914
  • 28
  • 75
  • 84

2 Answers2

2

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.

Vaughn Cato
  • 59,967
  • 5
  • 75
  • 116
  • so than there is no need to write `~Derived() { }` within `Derived` class since it's automaticly called and it doesn't make any operations specificly, right ? –  Apr 28 '13 at 17:56
1

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

alexrider
  • 4,419
  • 1
  • 15
  • 27