understanding copy constructor and copy assignment operator

121 views Asked by At

According to me in case 1 copy assignment operator is used so output should be 0 68 but it is 0 87 and in case 2 it is 87 87 which is fine.

#include <iostream>
using namespace std;
class numbered
{
  static int un;
public:
  int a;
  numbered (): a(un) {un++;}
  numbered(const numbered & n) : a(87){}
  numbered & operator=(const numbered) { a=68; return *this; }
};

int numbered::un=0;

void f(numbered  s){ cout<<s.a;}

int main()
{
  numbered a, b=a;
  cout << a.a << b.a;   //case 1
  f(a);f(b);        //case 2
  return 0;
}
2

There are 2 answers

0
user823738 On BEST ANSWER

It is working correctly.

To get your expected result:

numbered a, b;
b = a;
0
StoryTeller - Unslander Monica On

This

numbered a, b=a;

Can also be written like this:

numbered a, b(a);

This is a definition of several objects in a line. b is constructed here, so it's the copy c'tor that is called.