C++ - Operator Overloading
Here is the sample code for operator overloading.
I have overloaded the following three operators for the class MyValueClass.
1. operator = (assignment)
2. operator += (plus equal to)
3. operator + (plus)
I have overloaded assignment operator and operator += in the begining. You can see two implementation for binary arithmatic operator +. One with using the existing += operator and another one with out using += operator.
Source Code
class MyValueClass {
public:
int a;
int b;
public:
MyValueClass() { };
MyValueClass(int v1, int v2) : a(v1), b(v2) { };
MyValueClass(const MyValueClass& other)
{
this->a = other.a;
this->b = other.b;
}
const MyValueClass& operator = (const MyValueClass& other)
{
this->a = other.a;
this->b = other.b;
return *this;
}
MyValueClass& operator += (const MyValueClass& other)
{
this->a += other.a;
this->b += other.b;
return *this;
}
const MyValueClass operator + (const MyValueClass& other) const
{
MyValueClass m;
m.a = this->a + other.a;
m.b = this->b + other.b;
return m;
}
/*
// This is an alternate implementation for operator + using the operator +=
const MyValueClass operator + (const MyValueClass& other) const
{
MyValueClass m = *this;
m += other; // calling operator += , same as m.operator += (other);
return m;
}
*/
};
void main()
{
MyValueClass Obj1(5,10);
MyValueClass Obj2(15,20);
MyValueClass Obj3(25,30);
MyValueClass Obj4 = Obj1 + Obj2 + Obj3;
Obj2 += Obj3;
std::cout << "The value of Obj4 = " << Obj4.a << ", " << Obj4.b << "\n";
std::cout << "The value of Obj2 = " << Obj2.a << ", " << Obj2.b << "\n";
}
Output
The value of Obj4 = 45, 60
The value of Obj5 = 40, 50
|