Thursday, July 30, 2009

Is it a good practice to declare 'virtual' to C++ class destructors? If so why?

The typical rule is that if your class has at least one virtual function, you should always declare your class destructor as virtual.





Classes with virtual functions are usually designed to be used as base classes for other classes and because you can assign a pointer to a derived class to a base class pointer, a virtual destructor is needed to make sure that the derived classes destructor is called.





See the section (and code example) entitled "Why are destructors not virtual by default?" in Bjarne Stroustrup's (creator of the C++ language) C++ FAQ at the link below.


No comments:

Post a Comment