info@tutsfinder.in



Polymorphism


As the name suggest one name many forms, Polymorphism is the way of providing the different functionality by the functions having the same name based on the signatures of the methods.

For example: method calculate_area will definitely work for circle, square and triangle object.

There are two type of polymorphism in C++

1. Compile time polymorphism

2. Run time polymorphism

Method overloading

In Method overloading, functions have same name but different no. of arguments, return type of the parameters.

• It can be implemented in both parent and child class.

• It is also known as compile time polymorphism.



#include <iostream>
using namespace std;
void area(int);
void area(int,float);

int main() {

    int a = 5;
    float b = 10.5;

    area(a);
    area(a,b);

    return 0;
}

void area(int var) {
    cout << "Area of square : " << var*var << endl;
}

void area(int var1,float var2) {
    cout << "Area of rectangle  : " << var1*var2 << endl;
}


Output:

Area of square : 25
Area of rectangle  : 52.5


Method Overriding


In method overriding, redefining inherit methods in subclasses. In this, declaration should be identical, code may be different. It is like having another version of the same product.

• It can be used to add more functionality to a method.

• It is also called as run time polymorphism.

• In overriding, a method has same name, same no. of arguments and same data type.



#include <iostream>
using namespace std;
class BaseClass {
public:
   void display(){
      cout << "Parent Class";
   }
};
class DerivedClass: public BaseClass{
public:
   void display() {
      cout <<"Child Class";
   }
};
int main() {
   DerivedClass obj = DerivedClass();
   obj.display();
   return 0;
}


Output:

Child Class