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;
}
c0 = b2prints out 32944 correctly.c0 = b2callsc0 = C(b2),y.operator=(4) anda.operator=(4)C(b2)callsB(b2),A(1)(2) andcout << 9(9)B(b2)callsA(b2)A(b2)callscout << 3(3)From down to up: 3 2 9 4 and your final 4.