Operator overloading is a feature by which we can add custom functionality into operators to work with program defined types such as classes, structs etc.
In C++, operators are implemented as functions where operands become functions parameters. There are operators already defined in C++ for fundamental data types, however for program-defined types, we need to provide the extra functionalities. We provide these extra functionalities by overloading the operators.
For example, Int{1} + Int{2} would not work when compiled as C++ does not know how to add these two objects of Int. We need to overload + operator to add these two objects of Int.
We can overload + operator as follows to make above operation work:
class Int
{
int m_value{};
public:
Int() = default;
Int(int value)
: m_value{value}
{
}
friend Int operator+(const Int& v1, const Int& v2);
};
Int operator+(const Int& v1, const Int& v2)
{
return Int{v1.m_value + v2.m_value};
}Operator overloading methods
There are couple of ways to overload operators:
- Using friend function, as shown in above example.
- Using normal functions
- Using member functions