By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,586 Members | 1,173 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,586 IT Pros & Developers. It's quick & easy.

Virtual destructor for virtual base class?

P: n/a
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.
Jul 22 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Chunhui Han wrote:
...
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.

--
Best regards,
Andrey Tarasevich

Jul 22 '05 #2

P: n/a
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.

}
Jul 22 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.