As we saw in previous chapters, we are able to perform function overloading. Similarly we can also overload operators “+, -, =, *” and we call this concept as operator overloading.
Why do we need operator overloading?
Consider a simple example: Generally we use arithmetic addition operator to add integers. But there comes a case that you need to add or concatenate 2 strings. Or add the data members of 2 different objects of the same class. In such cases you can overload “+” operator with strings or class objects.
Then the compiler will decide on what appropriate function to be called.
Syntax for operator overloading or How to overload operator in C++?
Syntax:
class ClassName { public: <return_type> operator <symbol> (arguments) { //function body } };
For operator overloading, we need to use “operator” keyword.
In the line “<return_type> operator <symbol> (arguments)”.
<return_type> is the return type.
“operator” is the keyword used to define operator overloading
<symbol> symbol is the operator symbol you need to override like “+, -, =, *”
arguments: They are the arguments that you are passing to the function.
Points to remember for operator overloading in C++:
1. Operator overloading can be used to work with user-defined types only (class, structures). It cannot be used for built-in types.
2. Below operators cannot be overloaded in C++:
::, . , .*, ?:
3. Compiler will automatically override = and & operators by default.
Let us understand operator overloading with help of few examples:
1. Simple “++” operator overloading.
#include <iostream> using namespace std; class MyClass { private: int num; public: MyClass(): num(5){ } void operator ++ () { cout<<"The value of num before increment is "<<num<<endl; num = num + 1; cout<<"The value of num after increment is "<<num<<endl; } }; int main(void) { MyClass obj; ++obj; }
Output:
The value of num before increment is 5 The value of num after increment is 6
2. Simple “+” operator overloading, adding data members from 2 different objects.
#include <iostream> using namespace std; class MyClass { private: int num_1; int num_2; public: MyClass(int a, int b): num_1(a), num_2(b){ } friend MyClass operator + (MyClass &obj1, MyClass &obj2); void display() { cout<<"The value of num_1 "<<num_1<<" The value of num_2 "<<num_2<<endl; } }; MyClass operator + (MyClass &obj1, MyClass &obj2) { return MyClass(obj1.num_1+obj2.num_1, obj1.num_2+obj2.num_2); } int main(void) { MyClass obj_1(10, 20); MyClass obj_2(30, 40); MyClass obj_3 = obj_1 + obj_2; obj_3.display(); }
Output:
The value of num_1 40 The value of num_2 60