SyntaxRules SyntaxRules - 3 months ago 11
C++ Question

Static method class instatiation

How does a c++ line like this

Foo t3 = Foo::construct(true);
work when the default constructor is private? My assumption (which is obviously incorrect), is that the default constructor is called, followed my the assignment operator. That assumption must be incorrect because the default constructor is private, and cannot be called.

A concrete example:

class Foo {
private:
Foo() {}
bool bar;
public:
Foo(bool t): bar(t) {}
static Foo construct(bool t) {
Foo temp; //calling private constructor;
temp.bar = t;
return temp;
}
}


And a test method for instantiating this class looks like:

int main() {
//Foo t1; //Not allowed, compile error, Foo() is private
Foo t2(true); //Constructor, valid use
Foo t3 = Foo::construct(true); //It works! Why?
return 0;
}


What is really happening behind the scenes when
t3
is instantiated?

Answer
Foo t3 = Foo::construct(true); //It works! Why?

Because this is not default initiliazation followed by assignment but copy initialization

1) when a named variable (automatic, static, or thread-local) of a non-reference type T is declared with the initializer consisting of an equals sign followed by an expression.

So according to this statement:

If T is a class type and the cv-unqualified version of the type of other is T or a class derived from T, the non-explicit constructors of T are examined and the best match is selected by overload resolution. The constructor is then called to initialize the object.

and this:

If other is an rvalue expression, move constructor will be selected by overload resolution and called during copy-initialization. There is no such term as move-initialization.

implicitly declared move constructor is used in your case.

Comments