How does the default operator= works in C++?

101 Views Asked by At

I've had some hard times trying to understand how the default copy constructor and the default operator= work in C++.

In the following program, I don't see why the last line c0 = b2; cout <<endl; prints out 32944 .

-Does the operator= call the copy constructor if defined ? if not how does it behave ? in this case it seems that b0 when assingned to c0 used the copy constructor:

C(const B& x) : B(x), a(1){z=0; cout <<"9";}

-How did the statement c0 = b2; use the operator= of the class A (the 44 at the end of the result)?

#include <iostream>
using namespace std;

class A{
  public:
   A(){x=0; cout << "1";}
   A(int t) {x=t; cout << "2";}
   A(const A& a) {x=a.x; cout << "3";}
   const A& operator=(const A& a) {x=a.x; cout << "4"; return *this;}
  protected:
int x;
};

class B{
  public:
   B(const A& a=A()) : y(a) { cout << "5";}
   B(const A& b, int u){y=b; k=u; cout << "6";}
  protected:
   A y; int k;
};

class C : public B{
  public:
   C(int t=1) {z=t; cout <<"7"; }
   C(A x) : B(x) {z=0; cout <<"8";}
   C(const B& x) : B(x), a(1){z=0; cout <<"9";}
  protected:
   A a; int z;
};

int main(){
   B b2; cout << endl;
   C c0; cout <<endl;
   c0 = b2; cout <<endl;

   return 0; 
}
1

There are 1 best solutions below

2
273K On

c0 = b2 prints out 32944 correctly.

  1. c0 = b2 calls c0 = C(b2), y.operator= (4) and a.operator= (4)
  2. C(b2) calls B(b2), A(1) (2) and cout << 9 (9)
  3. B(b2) calls A(b2)
  4. A(b2) calls cout << 3 (3)

From down to up: 3 2 9 4 and your final 4.