Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent instantiation of base class that is not polymorphic c++

I have a base class that is not polymorphic, but I want to prevent it from being instantiated. Should I give this base class a pure virtual destructor to prevent it from being instantiated? But is it wrong or bad practice to give a non-polymorphic base class a virtual destructor?

like image 779
pkdc Avatar asked Jul 21 '15 10:07

pkdc


People also ask

How can you prevent a class from being instantiated?

Private constructors are used to prevent creating instances of a class when there are no instance fields or methods, such as the Math class, or when a method is called to obtain an instance of a class. If all the methods in the class are static, consider making the complete class static.

Who prevents to instantiate?

Private constructor: It will prevent to instantiate the Singleton class from outside the class. Static factory method: This provides the global point of access to the Singleton object and returns the instance to the caller.


2 Answers

To prevent a base class from being instantiated make all constructors protected.

like image 186
Niels Keurentjes Avatar answered Oct 06 '22 14:10

Niels Keurentjes


keep the ctor/dtor in protected scope.

like image 24
paper.plane Avatar answered Oct 06 '22 12:10

paper.plane