Search code examples
c++copy-constructorcopy-assignment

understanding copy constructor and copy assignment operator


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;
}

Solution

  • It is working correctly.

    To get your expected result:

    numbered a, b;
    b = a;