C++:polymorphism|Compile-time polymorphism

Operator overloading

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 overloading is realized by allowing operators to operate on user defined data with the same interface as that of the standard data types. 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.

The advantage of Operators overloading is to perform different operations on user defined data with the same interface as that of the standard data types.

To overload an operator we use a special class member function called the “operator” function. The operator function has the following format.

Syntax:
returntype operator op(argument list);

Here,
* “operator” is a keyword.
* “op” is the operator to be overloaded , it has to be a valid c++ operator, we cannot overload any arbitrary symbol to perform some operation.

Example of operator overloading

Example:1
Overloading increment operator (++)

// to overload ++ operator
#include<iostream>
#include<conio.h>
using namespace std;
class sample
{
private:
     int a;
public:
     sample();//defa
     sample(int n); //para
     void get();
     void disp();
     void operator++();
};
sample::sample()
{
     a=0;
}
sample::sample(int n)
{
     a=n;
}
void sample::get()
{
     cout<<"Enter the value of a ";
     cin>>a;
}
void sample::disp()
{
     cout<<"a= "<<a<<endl;
}
void sample::operator++()
{
     a=a+1;//a++;//++a;//a+=1;
}
int main()
{
  sample s1,s2;
  s1.get();
  s2.get();  //s1=10 s2=20
  s1.disp();
  s2.disp();
  ++s1; //s1.operator++();
  ++s1;
  ++s2;
  s1.disp();s2.disp();
  getch();
  return(0);
}

Output:

Enter the value of a 10
Enter the value of a 20
a= 10
a= 20
a= 12
a= 21