Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++11 private default constructor

Tags:

The following C++11 code compiles successfully on my GCC 4.8:

struct NonStack
{
private:
  NonStack() = default;
public:
  static NonStack* Create(){
    return new NonStack;
  }
};
NonStack a;

int main() { }

However the following gives a compilation error:

struct NonStack
{
private:
  NonStack(){}
};

NonStack a; 

int main() { }

Why does the first one succeed? Shouldn't the private defaulted constructor prohibit creation of an object via NonStack a;?

like image 455
thomas Avatar asked Sep 08 '14 02:09

thomas


People also ask

Is default constructor public or private?

By default, constructors are defined in public section of class.

Can a constructor be private in C?

Yes, a constructor can be private. And you can call it with member functions (static or non) or friend functions.

Can the constructor be private?

Yes, we can declare a constructor as private. If we declare a constructor as private we are not able to create an object of a class. We can use this private constructor in the Singleton Design Pattern.

Can you make constructors private C++?

Typically, constructors have public accessibility so that code outside the class definition or inheritance hierarchy can create objects of the class. But you can also declare a constructor as protected or private . Constructors may be declared as inline , explicit , friend , or constexpr .


1 Answers

This is gcc bug 54812, the compiler fails to respect access specifiers for explicitly defaulted special member functions. Bug 56429, which is marked as a duplicate of the earlier one, has a test case that is almost identical to the example in the question.

The solutions are to upgrade to gcc4.9, which resolves the issue. Or create an empty body for the constructor, instead of explicitly defaulting it, as you've done in the second example.

like image 171
Praetorian Avatar answered Sep 27 '22 21:09

Praetorian