Do virtual destructors have to be public?
c++, destructor
Solution
Do virtual destructors have to be public or are there situations where a non-public virtual destructor makes sense?
Horses for courses. You use a `public` virtual destructor if you need polymorphic deletion if not then your destructor does not need to be virtual at all.
Follow Herb's advice:
Guideline #4: A base class destructor should be either public and virtual, or protected and nonvirtual.
In brief, then, you're left with one of two situations. Either:
- You want to allow polymorphic deletion through a base pointer, in which case the destructor must be virtual and public; or
- You don't, in which case the destructor should be nonvirtual and protected, the latter to prevent the unwanted usage.
Problem
I find that almost every code snippet of virtual destructors has it as public member function, like this: ``` class Base { public: virtual ~Base() { cout << "~Base()" << endl; } }; class Derived : public Base { public: ~Derived() { cout << "~Derived()" << endl; } }; ``` Do virtual destructors have to be public or are there situations where a non-public virtual destructor makes sense?