Addition number to constuctor

Can anyone tell me how this code works?Thanks

#include<iostream>
using namespace std;
struct A{
A(){cout<<"Default Constructor"<<endl;}
A(int){cout<<"Int Constructor"<<endl;}
A(const A&){cout<<"Copy Constructor"<<endl;}
A& operator+(const A&v){cout<<"Operator+"<<endl;
return *this;
}
};
int main(){
A x;
A(x+1);
}
/*
The output is:
Default Constuctor
Int Constructor
Operator+
Copy Constructor
How??
*/
use the tag
[ code ][ /code ] (without spaces) to post code on the forum.
A x; < using the default connstructor.

A(x+1) < you first run what's inside the "()", and then the function. So let's anilize the "()".
x+1 < since the sum for class A is defined with another item of class A, it must be an A+A where the first A is the already instantiated x, while the second is a value. Since that value is not of class A, and it is expecting to see a class A item there, that "1" is equal to typing A(1), hence we have A(x+A(1)).
x+A(1)To perform the sum the second value must be instantiated, so we perform that constructor first. In order what happens is:
A(1) > x+previous_step > A(previous_step)
Hence
int constructor > sum (returns a new A) > copy constructor
When you post code, please wrap it in code tags [ code] your code here [/ code] (without the spaces). It will make it easier to read and comment on.

The line A x; calls the default constructor because there are no arguments when x is constructed.

For A(x+1); we first see that inside the parentheses, there is an operator+ happening on object x. Struct A only has operator+(const A&), so the code sees if the right hand side argument to operator+ (1 in this case) can be converted to an A object so the operator+ can happen. Luckily, struct A has a 1-argument constructor A(int) that takes an int and makes it into an A. So, A(1) is called, returning an anonymous object of type A which is passed to the operator+ function. Thus, the Int Constructor and Operator+ output lines.

Finally, the operator+ function returns a reference to an object or type A, specifically, a reference to the left hand side of the operator+ function. The A(x+1); line thus is calling the copy constructor using the result of the operator+ function as an argument.

Note that this A object is also anonymous, so you can't do anything with it, and it will immediately go out of scope. I you did want to manipulate this new object, you would need to assign it to a variable like A y(x+1);
Thanks a lot,now I understand
Topic archived. No new replies allowed.