Google News
logo
CPP - Interview Questions
What is operator overloading in C++?
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++. It is used to perform the operation on the user-defined data type. For example, C++ provides the ability to add the variables of the user-defined data type that is applied to the built-in data types.

Syntax of Operator Overloading : 
return_type class_name  : : operator op(argument_list)  
{  
     // body of the function.  
}  ​
* 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.

C++ Operators Overloading Example : 
#include <iostream>    
using namespace std;    
class Test    
{    
   private:    
      int num;    
   public:    
       Test(): num(8){}    
       void operator ++()         {     
          num = num+2;     
       }    
       void Print() {     
           cout<<"The Count is: "<<num;     
       }    
};    
int main()    
{    
    Test tt;    
    ++tt;  // calling of a function "void operator ++()"    
    tt.Print();    
    return 0;    
}
Output :
The Count is: 10
Advertisement