class test{
public:
int data;
test(const test& ){cout<<"INSIDE COPY CON "<<endl;}
test(int val = 0) : data(val){ cout<<"INSIDE CON "<<endl; }
test testfun(const test& obj)
{
cout<<"data : "<<data<<endl;
//test test3(this->data + obj.data);
//cout<<"test3 :"<<test3.data<<endl;
//return test3; //This will work only if return type is changed to const ref
return test(data + obj.data);
}
};
int main()
{
test testO1(1);
test testO2(2);
test testO3 = testO1.testfun(testO2);
cout<<testO3.data<<endl;
getchar();
}
OUTPUT:
INSIDE CON
INSIDE CON
data : 1
INSIDE CON
3
What happens when constructor is called in return statement? Since i am able to return by value and it works i think its not a temporary location. OR is it creating the object as a temporary and using copy constructor to copy the values , inthat case why is the print inside the copy constructor not getting printed.
You ask a penetrating question.
It is up to the compiler and the associated toolchain to decide what to do, but the basic pattern is as follows. Before calling
testfun(), the caller [main(), in your example] reserves space fortest03on the stack. It then passes the address oftest03totestfun().The function
testfun()must somehow put atestobject at the address the caller has supplied. If the function has only one return statement, it is free to use the storage provided by the caller to build the return value. It need not use its own storage. It can usemain()‘s.Now, this strategy does not always work. It typically fails when a function like
testfun()has two, distinct return statements, one or both of which return not a temporary but a named object. In that case, the compiler is forced to do an otherwise unnecessary copy-on-return. However, the more usual case resembles yours, in whichtestfun()just builds the return value directly in the spot in whichmain()wants it. In this case, no actual copy occurs.It is thus up to the compiler to decide whether the copy constructor is called on return in a case like this.