devxlogo

Use Protected Constructors to Block Undesirable Object Instantiation

Use Protected Constructors to Block Undesirable Object Instantiation

In order to block creation of class instances, you can declare its constructor as protected.

 class CommonRoot {	protected: CommonRoot(){}//no objects of this class can be instantiated};class Derived: public CommonRoot {public: Derived() {}};Derived d; // OK, constructor of d has access to any protected member in its base classCommonRoot cr; //compilation error: attempt to access a protected member of CommonRoot

The same effect of blocking instantiation of a class can be achieved with pure virtual functions. However, these add runtime and space overhead. When pure virtual functions aren’t needed, you can use a protected constructor instead.

devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist