C++: Protected Class Constructor

user542687 picture user542687 · Dec 24, 2010 · Viewed 7.3k times · Source

If a class is always going to be inherited, does it make sense to make the constructor protected?

class Base
{
protected:
    Base();
};

class Child : protected Base
{
public:
    Child() : Base();
};

Thanks.

Answer

Nawaz picture Nawaz · Dec 24, 2010

That only makes sense if you don't want clients to create instances of Base, rather you intend it to be base-class of some [derived] classes, and/or intend it to be used by friends of Base (see example below). Remember protected functions (and constructors) can only be invoked from derived classes and friend classes.

class Sample;
class Base
{
    friend class Sample;
protected:
    Base() {}
};

class Sample
{
 public:
   Sample()
   {
      //invoking protected constructor
      Base *p = new Base();
   }
};