I read that that virtual destructors must be declared in classes that have virtual methods. I just cant understand why they must be declared virtual. I know why we need to have virtual destructors as from the following example. I just wanted to know why compilers dont manage virtual destructors for us. Is there something I need to know about working of virtual destructors ?
The following example shows that if destructors are not declared virtual the destructors of derived class are not called why is that ?
class Base
{
// some virtual methods
public:
Base()
{std::cout << "Base Constructor\n";}
~Base()
{std::cout << "Base De-structor\n";}
};
class Derived : public Base
{
public:
Derived()
{std::cout << "Der constructor\n";}
~Derived()
{ std::cout << "Der De-structor\n";}
} ;
void main()
{
Base *b = new Derived();
delete b;
}
Because in C++, you pay for what you use. Having a
virtualdestructor by default involves the compiler adding a virtual table pointer to the class, which increases its size. This is not always desirable.The example exibits undefined behavior. It’s simply against the rules. The fact that not all destructors are called is just one possible manifestation. It could possibly crash.
Yes. They are required if you’re deleting an object through a pointer to a base class. Otherwise it’s undefined behavior.
5.3.5 Delete [expr.delete]