I need to setup a class inheritance structure, in which the abstract base class only holds member variables (but no member methods). The member methods will be defined by the derived classes. Hence, what I need is this post: Making a class abstract without any pure virtual methods
From the top 2 answers there, I realised there are 2 ways of achieving it:
I am curious to know the difference between the two approaches. Are there scenarios where one should be preferred over the other (or maybe some special situations where one would work but not the other)? I thought about it and could not think of anything.
I searched through the answers on some posts here ( Is there a use for making a protected destructor virtual? , C++: Protected Class Constructor , Should an abstract class' destructor be pure virtual? ) to try to put something together, but I could not come to a conclusion.
The main difference is in
Base * ptr = new Derived;
delete ptr;
With virtual destructor it is legal, without it there will be UB. Also dynamic_cast
requires at least one virtual function.
So if you want polymorphic behavior, use (pure) virtual destructor. If you don't want it, use protected constructor and don't pay overhead for polymorphism (vtables). But then declare destructor also protected, to prevent deleting via base pointer.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With