Protected constructor versus pure virtual destructor

I need to set up a class inheritance structure in which the abstract base class contains only member variables (but not member methods). Member methods will be defined by derived classes. Therefore, I need this post: Creating an abstract class without any pure virtual methods

From the first two answers there, I realized that there are two ways to achieve it:

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

I am curious to know the difference between these two approaches. Are there scenarios where you need to be preferred over others (or maybe with some special situations in which you could work, but not with others)? I thought about it and could not think of anything.

I searched for answers to some posts here ( Is it used to create a protected virtual destructor ? , C ++: Protected class constructor , Should the abstract class destructor be virtual? To try to collect something, but I could not come to a conclusion.

+6
source share
2 answers

The main difference is

Base * ptr = new Derived; delete ptr; 

With a virtual destructor, this is legal; without it, there will be UB. dynamic_cast also requires at least one virtual function.
Therefore, if you want polymorphic behavior, use a (pure) virtual destructor. If you do not want this, use a protected constructor and do not pay service data for polymorphism (vtables). But then declare the destructor also protected to prevent deletion using the base pointer.

+3
source

Both methods achieve the desired effect through the use of completely different mechanisms. In my opinion, the protected constructor more expressive, since it exactly matches the description of your problem. Pure virtual destructor not a natural solution and may require additional documentation to explain its purpose. It will also force subclasses to implement the destructor, even if it could be skipped.

+3
source

All Articles