3

I have a program which is showing weird behaviour

#include <cstdlib>
#include <iostream>

using namespace std;
class man{
           int i ;
      public:
           man(){
             i=23;
             cout << "\n defaul constructir called\t"<< i<<"\n";
           }
           man (const man & X) {
               i = 24;
           cout << "\n COPY constructir called\t"<< i<<"\n";
           }       
           man &  operator = (man x ) {
               i = 25;
               cout << "\n = operator  called\t"<< i<<"\n"; 
               return *this;
           }      
      };

int main(int argc, char *argv[])
{

     man x;
     cout <<"\n ----------\n";
     man y = x;
     cout <<"\n ----------\n";
     x=y;


    return 0;
}

The output shown in

 defaul constructir called  23

 ----------

 COPY constructir called    24

 ----------

 COPY constructir called    24

 = operator  called 25

This output is weird for the third call of x=y ;

Why is there an extra print of copy construtor called when I did not made a new object but am working with old objects .

Is it becuase of temporary objects in between and if yes can i stop them here ....

MAG
  • 2,599
  • 3
  • 25
  • 44

2 Answers2

12

Because your assignment operator takes its argument by value. You could take it by const reference instead.

Oliver Charlesworth
  • 260,367
  • 30
  • 546
  • 667
3
man& operator =(man x);

Your parameter takes its argument by-value, and when that happens it will invoke the copy-constructor. That's what's causing the extra unwanted call. Passing your argument by reference will avoid a copy, but then you will not be able to pass temporaries (commonly referred to as rvalues):

struct man
{
    man& operator =(man& x) { return *this; };
};

int main()
{
    man a, b;

    a = b;     // works
    a = man(); // error: no viable overloaded '=',
               // expected an l-value for 1st argument
}

Passing by reference to const will allow the copy-construction of both lvalues and rvalues:

man& operator =(man const& x);
//                  ^^^^^
David G
  • 90,891
  • 40
  • 158
  • 247