Reputation: 4874
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
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
Reputation: 141628
The code is:
A foo() {return A();}
When foo()
is called , the sequence of effects is:
A()
using A
's default constructor.A
created using copy/move constructor, with step 1's temporary as argument (that is, move constructor if it exists, otherwise copy constructor).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
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