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;
?
By default, constructors are defined in public section of class.
Yes, a constructor can be private. And you can call it with member functions (static or non) or friend functions.
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.
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 .
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With