6

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.

Community
  • 1
  • 1
Masked Man
  • 1
  • 7
  • 40
  • 80

2 Answers2

3

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.

SomeWittyUsername
  • 18,025
  • 3
  • 42
  • 85
  • I read that if you do not explicitly implement the destructor in a derived class, the one that's automatically generated for them is enough. So the pure virtual destructor does not force subclasses to implement their destructors. – Wutz Dec 05 '12 at 09:38
  • @Wutz, what's the purpose then? – Michael Krelin - hacker Dec 05 '12 at 10:24
  • @Michael Krelin - hacker: Making the base class abstract without pure virtual methods. It can be useful for allowing the base class to define default implementations for it's virtual methods and still preventing it from being directly instantiated. – Wutz Dec 05 '12 at 10:28
3

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.

Tadeusz Kopec for Ukraine
  • 12,283
  • 6
  • 56
  • 83
  • 1
    This does not *really* answer the OP's question. A non-pure virtual destructor could be used with the protected constructor case, and your example code will exhibit defined behavior. You are talking about a related, but orthogonal issue. – Thomas Eding Feb 11 '14 at 23:00