Criteria/Rules to Define the Operator Function

  1. In the case of a non-static member function, the binary operator should have only one argument and the unary should not have an argument.
  2. In the case of a friend function, the binary operator should have only two arguments and the unary should have only one argument.
  3. Operators that cannot be overloaded are  .* :: ?:
  4. Operators that cannot be overloaded when declaring that function as friend function are = () [] ->.
  5. The operator function must be either a non-static (member function), global free function or a friend function.

Refer to this, for more rules of Operator Overloading.

Types of Operator Overloading in C++

C++ provides a special function to change the current functionality of some operators within its class which is often called as operator overloading. Operator Overloading is the method by which we can change the function of some specific operators to do some different tasks.

Syntax:  

Return_Type classname :: operator op(Argument list)
{
Function Body
} // This can be done by declaring the function

Here,

  • Return_Type is the value type to be returned to another object.
  • operator op is the function where the operator is a keyword.
  • op is the operator to be overloaded.

Operator Overloading can be done by using three approaches, i.e.

  1. Overloading Unary Operator.
  2. Overloading Binary Operator.

Similar Reads

Criteria/Rules to Define the Operator Function

In the case of a non-static member function, the binary operator should have only one argument and the unary should not have an argument.In the case of a friend function, the binary operator should have only two arguments and the unary should have only one argument.Operators that cannot be overloaded are  .* :: ?:Operators that cannot be overloaded when declaring that function as friend function are = () [] ->.The operator function must be either a non-static (member function), global free function or a friend function....

1. Overloading Unary Operator

Let us consider overloading (-) unary operator. In the unary operator function, no arguments should be passed. It works only with one class object. It is the overloading of an operator operating on a single operand....

2. Overloading Binary Operator

In the binary operator overloading function, there should be one argument to be passed. It is the overloading of an operator operating on two operands. Below is the C++ program to show the overloading of the binary operator (+) using a class Distance with two distant objects....