0

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

enter image description here

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.

Community
  • 1
  • 1
Forever Learner
  • 1,465
  • 4
  • 15
  • 30
  • 3
    Read up on [_copy elision_](http://en.wikipedia.org/wiki/Copy_elision). This is why copy-constructors with side effects are Bad. – ildjarn May 03 '12 at 18:29
  • Your `number operator=` should be `number &operator=` and that function should be returning something (`*this`). – chris May 03 '12 at 18:30
  • Ah, Thanks @ildjarn, so it is compiler optimization. – Forever Learner May 03 '12 at 18:32
  • @CppLearner In a way. A statement like `number three = (any expression);` is an initialisation, not an assignment. – Mr Lister May 03 '12 at 18:33
  • @chris:: I deliberately returned by object instead of reference cause I was interested in knowing how many time copying happens. – Forever Learner May 03 '12 at 18:33
  • @Mr Lister : Yes, hence I am/was expecting copy ctor to be called. I think ildjarn comments solves my concerns. – Forever Learner May 03 '12 at 18:35
  • @ ildjarn : can you please put that as an answer. So I can can accept it. I can not accept my own answer for two day. I am not sure if I should keep the question or delete it. – Forever Learner May 03 '12 at 18:43
  • @CppLearner : I suspect it will get closed as a duplicate of [this question](http://stackoverflow.com/q/2143787/636019). If it doesn't, no harm in answering your own question. :-] – ildjarn May 03 '12 at 18:45
  • @ ildjarn : It is actually your answer :) I just wanted to close this quickly so tried put that as an answer with your due reference. – Forever Learner May 03 '12 at 18:47

0 Answers0