[C++] Operation Overloading - Assignment Operator
#include <iostream>
using namespace std;
class A
{
public:
int num;
A(int a) : num(a)
{}
};
int main(void)
{
A a1(1); //a1.num = 1
A a2(2); //a2.num = 2
a1 = a2; //a1.num = 2, a2.num = 2
cout<<"a1 = "<<a1<<endl;
cout<<"a2 = "<<a2<<endl;
}
Result
a1 = 2
a2 = 2
Basically, just like it's written in line17, assignment operator '=' is able to be operated by the class.
But think about the details of how it works.
The class is what 'developer' declared, and like other operators '= operator' need to be overloaded and fits in the class.
If 'operator=' is not overloaded, compiler will use 'default operator=' in line18.
And the progress of the default operator's copy is 'shallow copy', not 'deep copy'.
([C++] Shallow Copy & Deep Copy)
calling Assignment Operator in Class Inheritance
While calling constructor of derived class, the constructor of base class is called without any codes.
But in assignment operator, it doesn't work like that.
#include <iostream>
using namespace std;
class First
{
private:
int num1, num2;
public:
First(int n1=0, int n2=0) : num1(n1), num2(n2)
{ }
void ShowData() { cout<<num1<<", "<<num2<<endl; }
First& operator=(const First&ref)
{
cout<<"First& operator=()"<<endl;
num1=ref.num1;
num2=ref.num2;
return *this;
}
};
class Second : public First
{
private:
int num3, num4;
public:
Second(int n1, int n2, int n3, int n4)
: First(n1, n2), num3(n3), num4(n4)
{ }
void ShowData()
{
First::ShowData();
cout<<num3<<", "<<num4<<endl;
}
/**********************************
Second& operator=(const Second &ref)
{
cout<<"Second& operator=()"<<endl;
num3=ref.num3;
num4=ref.num4;
return *this;
}
**********************************/
};
int main(void)
{
Second ssrc(111, 222, 333, 444);
Second scpy(0, 0, 0, 0);
scpy=ssrc;
scpy.ShowData();
return 0;
}
Result
First& operator=()
111, 222
333, 444
without annotation
Second& operator=()
0, 0
333, 444
In the same context of overriding function in class inheritance, if you don't call base class's assignment operator in declaration of derived function's assignment operator, the members from base class are not copied.
So 'Second& operator=()' should be fixed.
Second& operator=(const Second& ref)
{
cout<<"Second& operator=()"<<endl;
First::operator = (ref);
num3 = ref.num3;
num4 = ref.num4;
return *this;
}
[참고자료]
- 윤성우의 열혈 C++ 프로그래밍