6
votes

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:

  • Make the destructor pure virtual.
  • Make the constructor protected.

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.

2

2 Answers

3
votes

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.

3
votes

Both ways achieve the desired effect by utilizing a completely different mechanisms. In my opinion a protected constructor is more expressive as it corresponds exactly to your problem description. Pure virtual destructor is not a natural solution and might require an additional documentation to explain its purpose. It will also force the subclasses to implement the destructor even if it could have been skipped.