Introduction
Operator overloading provides us a flexible option for the creation of new definitions for most C++ operators. In C++, we can make an operator work for user-defined classes. In simple words, C++ has the ability to provide the operators with special meaning for a data type. This mechanism of giving such special meaning to an operator is known as operator overloading. Operator overloading is a compile-time polymorphism. The main advantage of using operator overloading is to perform different operations on the same operand.
Syntax of operator overloading
return_type class_name operator symbol(arg_list)
{
function body // body of the function
}
In the above syntax,
- The return_type is the return type of the function.
- Next, the class_name is the name of the class.
- The operator is a keyword.
- The symbol is preceded by the keyword operator, and the operator symbol is the function name. Operator functions must be either member function or friend function.
- arg_list is the arguments passed by the function.
Also see, Literals in C.Fibonacci Series in C++
Rules for operator overloading
While operator overloading, we keep in mind the following measures
- The only existing operator can be overloaded. New operators can not be overloaded.
- Every overloaded operator must contain at least one operand of user-defined datatype.
- During operator overloading, we can not change the basic meaning of operators.
- If unary operators are overloaded by a member function, then they take no explicit arguments. But if they are overloaded through a friend function, then take one argument.
- If binary operators are overloaded by a member function, then they take one explicit argument. But, if they are overloaded through a friend function, then take two arguments.