SyntaxRules
SyntaxRules

Reputation: 2206

Static method class instantiation

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?

Upvotes: 0

Views: 67

Answers (3)

Slava
Slava

Reputation: 44238

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.

Upvotes: 3

grae22
grae22

Reputation: 104

The static construct method belongs to the class and can access the private constructor - this is often used when implementing the factory pattern.

Upvotes: 0

Mark B
Mark B

Reputation: 96241

Your line doesn't call the default constructor OR the copy-assignment operator.

It copy-constructs t3 from the temporary object returned from construct.

Upvotes: 2

Related Questions