Why explicitly delete the constructor instead of making it private?

How about:

//deleted constructor
class Foo
{ 
  public: 
    Foo() = delete;     
  public:
    static void foo();
};

void Foo::foo()
{
   Foo f;    //illegal
}

versus

//private constructor
class Foo
{ 
  private: 
    Foo() {}     
  public:
    static void foo();
};

void Foo::foo()
{
   Foo f;    //legal
}

They’re basically different things. private tells you that only members of the class can call that method or access that variable (or friends of course). In this case, it’s legal for a static method of that class (or any other member) to call a private constructor of a class. This doesn’t hold for deleted constructors.

Sample here.

Leave a Comment