Overloading in C++

05 min read

Compile time polymorphism: This type of polymorphism is achieved by function overloading or operator overloading.

  • Function Overloading: When there are multiple functions with the same name but different parameters then these functions are said to be overloaded. Functions can be overloaded by the change in the number of arguments or/and change in the type of arguments.
 
class Overload
{
public:
void func(int x)
{
cout << "value of x is " << x << endl;
}

void func(double x)
{
cout << "value of x is " << x << endl;
}

void func(int x, int y)
{
cout << "value of x and y is " << x << ", " << y << endl;
}
};

 
int main()
{
Overload obj1;
obj1.func(10);
obj1.func(9.1392);
obj1.func(80,74);
return 0;
}

 In the above example, a single function named func acts differently in three different situations which is the property of polymorphism.

 

  • Operator Overloading: C++ also provides option to overload operators. For example, we can make the operator (‘+’) for string class to concatenate two strings. We know that this is the addition operator whose task is to add to operands. So a single operator ‘+’ when placed between integer operands, adds them and when placed between string operands, concatenates them.

 

class Test
{
private:
int count;
public:
Test(): count(5){}
void operator ++() 
{ 
count
= count+1; } void Display() { cout<<"Count: "<<count; } }; int main() { Test t; ++t; t.Display(); return 0; }

In the above example, the operator ‘+’ is overloaded. The operator ‘+’ is an addition operator and can add two numbers(integers or floating point) but here the operator is made to perform addition of two imaginary or complex numbers.

 

2) Runtime polymorphism: This type of polymorphism is achieved by Function Overriding.

  • Function overriding on the other hand occurs when a derived class has a definition for one of the member functions of the base class. That base function is said to be overridden.
class BaseClass {
public:
   void disp(){
      cout<<"Function of Parent Class";
   }
};
class DerivedClass: public BaseClass{
public:
   void disp() {
      cout<<"Function of Child Class";
   }
};
int main() {
   DerivedClass obj = DerivedClass();
   obj.disp();
   return 0;
}

 

POST A NEW COMMENT
     
  • Input (stdin)

    Output (stdout)


    Input (stdin)

    Your Output (stdout)

    Expected Output

    Compiler Message

    Input (stdin)

    2    3

    Your Output (stdout)

    5

    Expected Output

    5

    Compiler Message

    5

    Error