Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will a base destructor always be called when a derived object is deleted?

Tags:

c++

say I have the following:

class Foo {
public:
void destroy();
~Foo()
{
   destroy();
}
};

class Bar : public Foo {
public:
~Bar() {}
};

If I have a Bar object, will Foo's destructor be called when the Bar objected is deleted?

Thanks

like image 613
jmasterx Avatar asked Dec 31 '25 09:12

jmasterx


1 Answers

Yes.

But the above code is dangerous; if you don't declare ~Foo() as virtual, then ~Bar() won't be called if you invoke delete on a Bar object via a Foo *.

like image 200
Oliver Charlesworth Avatar answered Jan 02 '26 01:01

Oliver Charlesworth



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!