• If a single object behaves in many ways, it is known as overloading.
  • It provides different versions of the same function while a single object has the same name.
  • C++ facilitates you to specify more than one definition for an operator or a function in the same scope.
  • Overloading consists of two types, they are:
    • Operator Overloading
    • Function Overloading

Operator Overloading

  • Operator overloading is otherwise known as compile-time polymorphism in which a standard operator is overloaded to provide a user-defined definition to it.
  • ‘+’ operator is overloaded to perform the addition operation on data types such as float, int, etc.
  • In following functions operator overloading can be implemented such as Member function, Non-Member function, Friend Function.

Sample Code

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

Function Overloading

  • Function overloading is a type of compile-time polymorphism which can define a family of functions with the same name.
  • The function would perform different operations based on the argument list in the function call.
  • In argument list function to be invoked depends on the number of arguments and the type of the arguments.

Sample Code

using namespace std;    
class Cal {
public:
static int add(int a,int b){
return a + b;
}
static int add(int a, int b, int c)
{
return a + b + c;
}
};
int main(void) {
Cal C; // class object declaration.
cout<<C.add(10, 20)<<endl;
cout<<C.add(12, 20, 23);
return 0;
}

Output

Categorized in: