I found this same code here: https://stackoverflow.com/a/5854862/257299
struct Base { virtual Base& operator+=(int) = 0; };
struct X : Base
{
X(int n) : n_(n) { }
X& operator+=(int n) { n_ += n; return *this; }
int n_;
};
struct Y : Base
{
Y(double n) : n_(n) { }
Y& operator+=(int n) { n_ += n; return *this; }
double n_;
};
void f(Base& x) { x += 2; } // run-time polymorphic dispatch
I have read many Q&As about when (and when not) to use a virtual destructor, but I am stumped by this sample code. My textbook understanding of C++ says: "Aha! A base class without a virtual destructor is bad. Memory leak or undefined behaviour may occur." I also think this style appears in the C++ standard library, but I don't know an example off the top of my head.
What happens if I use X
(and Y
) as such...?
X* x = new X(5);
// Scenario 1
delete x; // undefined behaviour...? Does default dtor for `Base` get called?
// Scenario 2
Base* b = x;
delete x; // undefined behaviour...?
Perhaps I am confused about (a) using a class safely without a virtual destructor versus (b) safety-by-design / I cannot get it wrong.
In case (a), to use safely, only stack allocate. This requires discipline!
In case (b), either add a virtual destructor in Base
or force stack allocation via a private constructor and public static factory method. This does not require discipline. (Although this comment from David Rodríguez confused me more! "Why would you want to do this [prevent heap allocation]?")