Operator Overloading

Operator Overloading

You can redefine or overload most of the built-in operators available in C++. Thus, a programmer can use operators with user-defined types as well.
Overloaded operators are functions with special names: the keyword "operator" followed by the symbol for the operator being defined. Like any other function, an overloaded operator has a return type and a parameter list.
Operator overloading is a compile-time polymorphism in which the operator is overloaded to provide the special meaning to the user-defined data type.Operator overloading is used to overload or redefines most of the operators available in C++.
Operator that cannot be overloaded are as follows:
  • Scope operator (::)
  • Sizeof
  • member selector(.)
  • member pointer selector(*)
  • ternary operator(?:)

Syntax of Operator Overloading

  1. return_type class_name  : : operator op(argument_list)  
  2. {  
  3.      // body of the function.  
  4. }  
Where the return type is the type of value returned by the function.
class_name is the name of the class.
operator op is an operator function where op is the operator being overloaded, and the operator is the keyword.

Rules for Operator Overloading

  • Existing operators can only be overloaded, but the new operators cannot be overloaded.
  • The overloaded operator contains atleast one operand of the user-defined data type.
  • We cannot use friend function to overload certain operators. However, the member function can be used to overload those operators.
  • When unary operators are overloaded through a member function take no explicit arguments, but, if they are overloaded by a friend function, takes one argument.
  • When binary operators are overloaded through a member function takes one explicit argument, and if they are overloaded through a friend function takes two explicit arguments.

C++ Operators Overloading Example

Let's see the simple example of operator overloading in C++. In this example, void operator ++ () operator function is defined (inside Test class).
// program to overload the unary operator ++.
  1. #include <iostream>    
  2. using namespace std;    
  3. class Test    
  4. {    
  5.    private:    
  6.       int num;    
  7.    public:    
  8.        Test(): num(8){}    
  9.        void operator ++()         {     
  10.           num = num+2;     
  11.        }    
  12.        void Print() {     
  13.            cout<<"The Count is: "<<num;     
  14.        }    
  15. };    
  16. int main()    
  17. {    
  18.     Test tt;    
  19.     ++tt;  // calling of a function "void operator ++()"    
  20.     tt.Print();    
  21.     return 0;    
  22. }    
Output:
The Count is: 10




Comments