Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Oct 5, 1998

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 class
CommonRoot 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.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date