Main BLOGGER
Google
WWW THIS BLOG
Monday, January 22, 2007
 
C++ virtual destructor
5.3.5.3: "If the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand's dynamic type and the static type shall have a virtual destructor or the behavior is undefined."

1. If C++ had a "sealed" keyword, then the rule would be simpler: If you do a "delete p" where p is a pointer to an unsealed class, then that class needs have a virtual destructor. (The imaginary "sealed" keyword makes it explicit when a class can act as the base class for another class.)

2. If the sizeof or layout of your class is a concern for some reason, making the destructor virtual "costs nothing" if your base class already has a virtual method. You're already carrying a vptr at that point.

3. Classes having virtual functions should always have a virtual destructor. This is necessary since it is likely that you will hold an object of a class with a pointer of a less derived type. Making the destructor virtual ensures that the right code will be run if you delete
the object via the pointer
--
Pop (Pu Liu)



<< Home

Powered by Blogger

Google
WWW THIS BLOG