Virtual destructor for virtual base class?

C

Chunhui Han

Hi,

I was recently reading about virtual base classes in C++. The book I was
reading says that it is illegal to have non-virtual destructor for the
virtual base class. It seems to me that virtual destructors are essential
when the class has virtual functions, since this class is supposed to be
used as a base class for polymorphism. But what is the real reason for a
virtual destructor in a virtual base class?

Thanks,
C.H.
 
A

Andrey Tarasevich

Chunhui said:
...
I was recently reading about virtual base classes in C++. The book I was
reading says that it is illegal to have non-virtual destructor for the
virtual base class.

The book is wrong (assuming that it really says exactly that). It is not
illegal.
It seems to me that virtual destructors are essential
when the class has virtual functions, since this class is supposed to be
used as a base class for polymorphism.

Virtual destructors are essential for one and only one thing:
polymorphic deletion of objects of class type. If you are trying to
delete an object of derived class thorough a pointer to one of its
direct or indirect base class subobjects, you need virtual destructor in
that base class. Virtual inheritance is not different from regular
inheritance in this respect.

The above is a formal rule. Another rule, that says that classes with
virtual functions should have virtual destructors is less formal, but
good enough to be used in practice in most (if not all) cases.
But what is the real reason for a
virtual destructor in a virtual base class?

Polymorphic deletion. Regardless of base class' being virtual or not.
 
J

JKop

Chunhui Han posted:
Hi,

I was recently reading about virtual base classes in C++. The book I was
reading says that it is illegal to have non-virtual destructor for the
virtual base class. It seems to me that virtual destructors are essential
when the class has virtual functions, since this class is supposed to be
used as a base class for polymorphism. But what is the real reason for a
virtual destructor in a virtual base class?

Thanks,
C.H.

class A
{
public:

virtual void poo(void) = 0;


};


class B : public A
{
public:

virtual void poo(void)
{
;
}

};


int main(void)
{
A* pA = new B;


delete pA;

//In the above delete, if class A's destructor is NOT declared virtual,
//Then the dstructor for class B will never be called.

}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,049
Latest member
Allen00Reed

Latest Threads

Top