The link that
Return 0 posted makes some factual errors -- so I wouldn't consider it final [pun intended]. (I think it was written by someone trying to figure things out for himself.)
Virtual Destructors
The purpose of virtual destructors is to handle proper destruction from a base class pointer.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
#include <iostream>
using namespace std;
#define VIRTUAL virtual
//#define VIRTUAL
struct base
{
base() { cout << "base ctor\n"; }
VIRTUAL ~base() { cout << "base dtor\n"; }
};
struct derived: public base
{
derived() { cout << "derived ctor\n"; }
virtual ~derived() { cout << "derived dtor\n"; }
};
int main()
{
base* p = new derived;
cout << "\nNow for the fun\n\n";
delete p;
cout << "\nBye bye\n\n";
return 0;
}
|
Try the code with VIRTUAL defined as nothing also to see the difference. Unless the base class has a virtual destructor calling the destructor through a base class pointer will fail to call derived class constructors.
You don't need a virtual destructor if you don't plan to destruct from a base class pointer. Replace main() with the following and try again...
1 2 3 4 5 6 7 8 9
|
int main()
{
{
derived p;
cout << "\nNow for the fun\n\n";
}
cout << "\nBye bye\n\n";
return 0;
}
|
It works both ways...
(Notice that the derived class's destructor does
not need to be virtual -- but in general it should be.)
Keywords like Java's
final is really a bit of fluff. In C++, to accomplish a non-inheritable class, you should have it listed in big bold letters that you should not inherit from the class.
1 2 3 4 5 6
|
//
// Hey! D O N ' T I N H E R I T from this class!
//
// Your interocitor will fry.
//
class Quux
|
Against the usual 'document once' philosophy, I recommend it be indicated
- in the header file
- in the source file
- in the documentation
Personally, however, I don't understand why people have such a thing for making classes un-inheritable. The whole point of classes is to be inheritable. Exactly how often can you really say, "Hey, there is never going to be a need to inherit from this class...".
The purpose of inheritance is upgradability and maintainability. Make a class final and you are back in the dark ages of maintenance.
Hope this helps.
Well, off to get my toe X-Rayed. :-|