C++

C++’s Polymorphism – Detailed Instructions From [A-Z]

OOPs’ polymorphism feature enables an object to act differently under various circumstances. There are two varieties of polymorphism in C++:
1) Static (or early) binding is another name for compile-time polymorphism.
2) Runtime Polymorphism, commonly referred to as late or dynamic binding.

1) Compile time Polymorphism

Overloading of operators and functions is a prime example of compile-time polymorphism.

Example of Compile Time Polymorphism

Two functions with the same name and varying numbers of arguments are shown in this example. This is an example of polymorphism since the function that is called depends on how many parameters we supply when calling it, and the result varies depending on the circumstances. Build time polymorphism gets its name since the call is decided upon at compile time.

#include <iostream>
using namespace std;
class Add {
public:
  int sum(int num1, int num2){
     return num1+num2;
  }
  int sum(int num1, int num2, int num3){
     return num1+num2+num3;
  }
};
int main() {
  Add obj;
  //This will call the first function
  cout<<"Output: "<<obj.sum(10, 20)<<endl;
  //This will call the second function
  cout<<"Output: "<<obj.sum(11, 22, 33);
  return 0;
}

Output:
Output: 30
Output: 66

2) Runtime Polymorphism

Runtime polymorphism is demonstrated by function overriding.
Function overriding, in this case when the child class overrides the parent class, is the act of a child class declaring a method that is already present in the parent class.

When a function is overridden, there are two definitions of it—one in the parent class and one in the child class. Runtime polymorphism derives its name from the fact that the call to the function is determined at runtime in order to choose which definition of the function is to be called.

Runtime Polymorphism Example

#include <iostream>
using namespace std;
class A {
public:
  void disp(){
     cout<<"Super Class Function"<<endl;
  }
};
class B: public A{
public:
  void disp(){
     cout<<"Sub Class Function";
  }
};
int main() {
  //Parent class object
  A obj;
  obj.disp();
  //Child class object
  B obj2;
  obj2.disp();
  return 0;
}

Output:

Super Class Function
Sub Class Function

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button