Sebastian Lenartowicz
Sebastian Lenartowicz

Reputation: 4874

What constructor is called in this case?

Let's say I have an object

class A {
    public:
    int bar();
};

A foo() {return A();}
int A::bar() {return 5;}

And then I do this:

int i = foo().bar();

What constructor is invoked for the temporary value created when foo() returns?

Upvotes: 0

Views: 68

Answers (3)

user6697869
user6697869

Reputation:

The default constructor is called. Maybe trying this makes it clearer:

#include <iostream>

using namespace std;

class A {
public:
  A() {
    cout << "A's default ctor" << endl;
  }
};

int main() {
  A a;
  return 0;
}

Upvotes: 0

M.M
M.M

Reputation: 141628

The code is:

A foo() {return A();}

When foo() is called , the sequence of effects is:

  1. Temporary created by A() using A's default constructor.
  2. Return value object of type A created using copy/move constructor, with step 1's temporary as argument (that is, move constructor if it exists, otherwise copy constructor).
  3. Temporary from step 1 is destructed.

However this is a copy elision context, so the compiler might combine all 3 steps into one, and create the return value object using A's default constructor.

What happens to the return value object depends on what the calling code does. There might be further copy elision. In the usage:

int i = foo().bar();

nothing else happens; bar() is called on the return value object, the value is assigned to i, and then the return value object is destroyed.

Upvotes: 1

halit
halit

Reputation: 177

If you are compiling with C++11, inside foo when return A() ran it calls default constructor. Then when it returns from foo move constructor is called. But if you're compiling with older versions first default constructor is called then copy constructor is called.

Upvotes: 0

Related Questions