Important Notice: Our web hosting provider recently started charging us for additional visits, which was unexpected. In response, we're seeking donations. Depending on the situation, we may explore different monetization options for our Community and Expert Contributors. It's crucial to provide more returns for their expertise and offer more Expert Validated Answers or AI Validated Answers. Learn more about our hosting issue here.

What is a virtual destructor?

destructor virtual
0
10 Posted

What is a virtual destructor?

0
10

Ans: The simple answer is that a virtual destructor is one that is declared with the virtual attribute. The behavior of a virtual destructor is what is important.

0

In general, a virtual fn means to start at the class of the object itself, not the type of the pointer/ref (“do the right thing based on the actual class of” is a good way to remember it). Virtual destructors (dtors) are no different: start the destruction process “down” at the object’s actual class, rather than “up” at the ptr’s class (ie: “destroy yourself using the *correct* destruction routine”). Virtual destructors are so valuable that some people want compilers to holler at you if you forget them. In general there’s only one reason *not* to make a class’ dtor virtual: if that class has no virtual fns, the introduction of the first virtual fn imposes typically 4 bytes overhead in the size of each object (there’s a bit of magic for how C++ “does the right thing”, and it boils down to an extra ptr per object called the “virtual table pointer” or “vptr”).

Related Questions

What is your question?

*Sadly, we had to bring back ads too. Hopefully more targeted.