One of the beautiful features of ‘C++’ is its ability to support Operator Overloading. ‘C++’ Operator Overloading allows changing the behavior of operators when using them with ‘C++’ class objects.
One of the best examples of Operator Overloading is the ‘+’ operator. Usually, the ‘+’ operator will add two integer operands and produce an integer result. For the string class, the ‘+’ operator will be used to concatenate two strings. This is achieved by overloading the ‘+’ operator for the string class.
Operator Overloading provides the flexibility to write more meaningful and readable code.
‘C++’ allows to overload almost all the operators; except Scope Resolution Operator (“::”), Member Selection Operator (“.”), and (“.*”).
The syntax of operator overloading is:
<return type> operator <op>(<arguments>);
Here the operator is the keyword indicates this is the operator overloading function.
- <op> is the actual operator we are going to overload. It will be +, -, *, or any other operator ‘C++’ allows to overload.
- <return type> is the return type the operator overloading function returns.
- <arguments> is zero or more arguments. The number of arguments depends on the type of operator you are going to overload.
Let us take a simple example.
// sample.cpp #include <iostream> #include <string.h> using namespace std; class Sample { private: char m_str[1024]; public: Sample(const char *str) { strcpy(m_str, str); } Sample operator +(Sample obj) { strcat(m_str, obj.getstr()); return Sample(m_str); } char *getstr() { return m_str; } }; // main // int main() { Sample sample("Hello!"); cout << (sample + " World!").getstr() << endl; return 0; }
In this example, we have created a Sample class that holds a string. We have overloaded the ‘+’ operator to merge the string with the string inside the Sample class.
Compile and run the program to see the results.
// Malin