118

Why would anyone declare a constructor protected? I know that constructors are declared private for the purpose of not allowing their creation on stack.

9 Answers 9

139

When a class is (intended as) an abstract class, a protected constructor is exactly right. In that situation you don't want objects to be instantiated from the class but only use it to inherit from.

There are other uses cases, like when a certain set of construction parameters should be limited to derived classes.

11
  • 10
    +1 But the doesn't necessarily have to be an abstract class. It's often the case though.
    – rtn
    Jun 29, 2009 at 8:59
  • 4
    Isn't it sufficient to declare a function to be pure virtual for defining a base class? Or the above is in absence of pure virtual function. What is a creation event for a Derived class of such an Abstract class?
    – Amol Gawai
    Jun 29, 2009 at 12:41
  • 7
    Neil, I am not waging a language war here, just answered what protected ctor is good for. But you should be able to appreciate that there is a design-level concept of abstract class, and that it differs from the C++/Delphi definition. Jun 29, 2009 at 13:43
  • 8
    The canonical way to indicate a class is abstract is to make the destructor pure virtual. But I tend to make the constructors protected as well, both for "belt and suspenders" protection, and to make it clear to clients they cannot directly instantiate an object of the class.
    – JohnMcG
    Jun 29, 2009 at 13:58
  • 2
    Combining with answers and comments, this answer is good for me to accept.
    – Amol Gawai
    Jun 30, 2009 at 5:45
16

Non-public constructors are useful when there are construction requirements that cannot be guaranteed solely by the constructor. For instance, if an initialization method needs to be called right after the constructor, or if the object needs to register itself with some container/manager object, this must be done outside the constructor. By limiting access to the constructor and providing only a factory method, you can ensure that any instance a user receives will fulfill all of its guarantees. This is also commonly used to implement a Singleton, which is really just another guarantee the class makes (that there will only be a single instance).

The reason for making the constructor protected, rather than private, is the same as for making any other method or field protected instead of private: so that it can be inherited by children. Perhaps you want a public, non-virtual factory method in the base class, which returns references to instances of the derived classes; the derived classes obviously want access to the parent constructors, but you still don't want to be creating them outside of your factory.

1
  • "any instance a user receives will fulfill all of its guarantees."...isn't also the derived/child class inheriting all of the parent class?
    – Cloud Cho
    Mar 14 at 18:55
12

A protected constructor can be used to make a class effectively abstract when none of its methods are pure-virtual.

It is not quite abstract in the C++ sense since friend classes can still use it without overriding, but then you would have to declare these.

10

A protected constructor means that only derived members can construct instances of the class (and derived instances) using that constructor. This sounds a bit chicken-and-egg, but is sometimes useful when implementing class factories.

3
  • 4
    Technically, this applies only if ALL ctors are protected.
    – MSalters
    Jun 29, 2009 at 9:09
  • 2
    friend classes can also call the protected constructor (not just derived classes). Sep 29, 2013 at 3:48
  • ...and a use of a friend class calling the protected constructor would be in the case of an object that has members that are constant (set by the constructor) but need to be public, but never to be set by any other public access, guarantees that the object wont be created somewhere else and the data therefore would not be modified anywhere else either. Mar 2, 2014 at 17:37
8

one use could be factory patterns

1
  • 8
    It would be great if you can elaborate your answer by adding some practical examples. Jan 4, 2019 at 22:50
6

For factory methods with side-effects.

class mine {

  private:
    mine () {};

  protected:
    mine(int id) : m_id(id) {};

   int m_id;
   static int m_count;

  public:
    static mine* CreateOneOfMe() {
         return mine(m_count++);
    }

    int GetId() { return m_id; }

 };

This creates instances of the class and guarantees that each of them has a unique incrementing integer id. Note that if the constructor you want to use is not the default, you must hide the default too.

1
  • 1
    You could also just not declare the default constructor and it wouldn't exist.
    – foxesque
    Jul 22, 2020 at 8:15
5

To let a subclass use a constructor that should not be accessible to an instantiator directly.

3

You could use it to limit the classes that could create it, for example:

class Level
{
private:

 Level();
 ~Level();

 friend class LevelManager;
};

The only class that can create an instance of it is the LevelManager class, so you will always know that the Level instance is created in the LevelManager.

1
  • 1
    While true, that's a private constructor, not protected.
    – David
    Jun 29, 2009 at 13:11
2

One use of protected constructor is to implement the CRTP pattern, see the code below:

#include <iostream>
#include <assert.h>

template <class T>
class ComparableMixin {
public:
    bool operator !=(ComparableMixin &other) {
        return ~(*static_cast<T*>(this) == static_cast<T&>(other));
    }
    bool operator <(ComparableMixin &other) {
        return ((*(this) != other) && (*static_cast<T*>(this) <= static_cast<T&>(other)));
    }
    bool operator >(ComparableMixin &other) {
        return ~(*static_cast<T*>(this) <= static_cast<T&>(other));
    }
    bool operator >=(ComparableMixin &other) {
        return ((*static_cast<T*>(this) == static_cast<T&>(other)) || (*(this) > other));
    }
protected:
    ComparableMixin() {}
};

class Integer: public ComparableMixin<Integer> {
public:
 Integer(int i) {
     this->i = i;
 }
 int i;
 bool operator <=(Integer &other) {
     return (this->i <= other.i);
 }
 bool operator ==(Integer &other) {
     return (this->i == other.i);
 }
};
int main() {

    Integer i(0) ;
    Integer j(1) ;
    //ComparableMixin<Integer> c; //compilation error!
    assert (i < j );
    assert (i != j);
    assert (j >  i);
    assert (j >= i);

    return 0;
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.