Reading from Herb Sutter, I can see this point:
Guideline #4: A base class destructor should be either public and >virtual, or protected and nonvirtual.
However, I am struggling to understand the reasons behind the latter. -- having a non-virtual destructor... I do understand why it needs to be protected.
here is my code:
#include <iostream>
using namespace std;
class base {
public:
base () {cout << "base ctor" << endl;}
virtual void foo () = 0;
protected:
~base() {cout << "base dtor" << endl;}
};
class derived : public base {
public:
derived () {cout << "derived ctor" << endl;}
virtual void foo () override {cout << "derived foo" << endl;}
virtual ~derived(){cout << "derived dtor" << endl;}
};
int main(){
derived* b = new derived();
delete b;
cout <<"done"<<endl;
}
What do I gain by making the base dtor non-virtual vs virtual? I can see the same effect whether its virtual or non-virtual.
base ctor
derived ctor
derived dtor
base dtor
done