9

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.

  • There's no need to explicitly initialize the `Base`, by the way. – GManNickG Dec 24 '10 at 05:13
  • @GMan This is not an accurate example of what I am doing. I just did as little code as I could, while still getting my point across. –  Dec 24 '10 at 05:26

2 Answers2

11

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();
   }
};
Nawaz
  • 353,942
  • 115
  • 666
  • 851
4

If it's always going to be a base (a "mixin"), yes. Keep in mind a class with pure virtual functions will always be a base, but you won't need to do this since it cannot be instantiated anyway.

Also, give it either a public virtual destructor or a protected non-virtual destructor.

GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • Just realized that a protected non-virtual destructor would be the right fix for some classes I've written that are used polymorphically but never deleted polymorphically. I never could get rid of the compiler warning suggesting a virtual destructor, but this might just do it. – Ben Voigt Dec 24 '10 at 05:17
  • If this matters, at this time, I don't plan on having any pure virtual functions. –  Dec 24 '10 at 05:22
  • 1
    @Jay: So then if it doesn't make sense for the class to be used as anything but a base, make a protected constructor. – GManNickG Dec 24 '10 at 05:38
  • @Jay: No problem. Just don't fall into the trap of confusing "It shouldn't be used without being a base." with "I'll never use it without it being a base."; the latter doesn't imply the former. – GManNickG Dec 24 '10 at 06:13