Possible Duplicate:
Why copy constructor is not called in this case?
What is copy elision and how does it optimize the copy-and-swap idiom?
I was playing around trying to understand ctors and operator overloading.
#include <iostream>
using namespace std;
class number {
int n;
public:
number(int i=0):n(i) { cout<<"in ctor"<<endl; }
~number() { cout<<"in dtor"<<endl; }
number(const number& obj):n(obj.n) {
cout<<"in copy ctor"<<endl; }
number operator+(const number & obj) {
return number(n+obj.n); }
number operator=(const number &rhs) {
n = rhs.n; cout<<"in assignemnt opr"<<endl; }
void disp() {cout<<n<<endl;}
};
int main()
{
number one(1),two(2);
number three =one + two; //was expecting copy ctor being called here
three.disp();
}
When I ran the above code I got the following output
I understand that three constructors are called for one
, two
and un-named
object in the overloaded +
operator.I am unable to understand how three
is constructed.I thought copy ctor should be called.But It seems like it is not.
Can some one please explain me. Thanks.