Reputation: 27581
Guideline #4 link text, states:
A base class destructor should be either public and virtual, or protected and nonvirtual.
Probably I'm missing something, but what if I just create a concrete class, that is not designed to be used as base class.
Should I declare it's destructor public and virtual? By this I'm implicitly declate that my class is "ready to be used as base class", while this is not necessary true.
Upvotes: 0
Views: 575
Reputation: 254431
The advice refers to classes with virtual functions, intended to be polymorphic base classes. You have to make sure that if someone calls delete
on a base class pointer, then the destructor of the actual class is called; otherwise, resources allocated by the derived classes won't be freed.
There are two ways to achieve this:
delete
on a base class pointer.For a concrete class that won't be used as a base class, you will only ever call delete
on a pointer to the actual type, so the advice doesn't apply. It should have a public non-virtual destructor if it needs one.
Upvotes: 0
Reputation: 7828
Your destructor only needs to be virtual if your class will be extended later. I'm not aware of a case where you'd want a protected/private destructor.
It's worth noting that if you have even one virtual method, you lose nothing (with most compilers) making the destructor virtual as well (but it will protect you in case somebody extends later).
Upvotes: 0
Reputation: 13036
Destructor SHALL BE virtual in any of the following cases:
Rare exception:
Regarding public or protected - in general it is more question of how you intend to control access to destructor.
Upvotes: 0
Reputation: 59811
Consider it another way around: Do you know that no one will absolutely ever try to derive from your class and when somebody does do you think he will remember to take a closer look at your dtor? Sometimes people use inheritance over composition for a good reason (provide the full interface of your class without having ugly getter syntax).
Another point for the virtual dtor is the Open/Closed Principle.
I'd go with the virtual dtor if you are not concerned with hard real-time performance or something alike.
Upvotes: 0
Reputation: 564363
The link text specifically says"A base class destructor should be"...
The guidelines are only meant for a class which is designed to be used as a base class. If you are making a single, concrete class that will not be used as a base class, you should leave the public constructor non-virtual.
Upvotes: 5
Reputation: 4360
If nothing else in your class is virtual, I don't think the destructor should be virtual either.
Upvotes: 0