C++ Operator Overloading
C++ provides the ability to redefine the behavior of the built-in operators for user-defined data types. This feature is known as operator overloading. Operator overloading allows us to provide a new implementation of the operator to work with user-defined data types.
For example, you can overload the addition operator '+' to add two complex numbers, which is not supported by the built-in implementation of the operator. Operator overloading can be used to create more intuitive and readable code.
How to Overload Operators in C++?
The operator overloading can be done in two ways:
-
Member Function: An operator function is a member function if it is a member of a class. An operator function can access the member variables and other member functions of the class. To overload an operator as a member function, the operator keyword must be followed by the operator symbol and then the function name.
-
Friend Function: An operator function is a friend function if it is not a member of a class, but has access to the private and protected members of the class. To overload an operator as a friend function, the friend keyword must be used before the function definition and the function must be declared as a friend in the class.
Example: Overloading the + operator for Complex Numbers
1#include <iostream> 2using namespace std; 3 4class Complex 5{ 6private: 7 int real, imag; 8 9public: 10 Complex(int r = 0, int i =0) 11 { real = r; imag = i; } 12 13 // This is automatically called when '+' is used with 14 // between two Complex objects 15 Complex operator + (Complex const &obj) { 16 Complex res; 17 res.real = real + obj.real; 18 res.imag = imag + obj.imag; 19 return res; 20 } 21 22 void print() 23 { cout << real << " + i" << imag << endl; } 24}; 25 26int main() 27{ 28 Complex c1(10, 5), c2(2, 4); 29 Complex c3 = c1 + c2; // An example call to "operator+" 30 c3.print(); 31 return 0; 32}
Output:
12 + i9
This is just one example of operator overloading. Other operators such as '-', '*', '/', etc. can also be overloaded in a similar manner. However, it is important to keep in mind that not all operators can be overloaded, and some have restrictions on how they can be overloaded.