Thursday, October 3, 2019

Polymorphism

Run time Polymorphism(Function Overriding)
****************************************************
Function overriding means when the child class contains the method which is already present in the parent class.
#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"<<endl;
        
    }
};

int main()
{
    A obj;
    obj.disp();
    
    B obj2;
    obj2.disp();
    
    return 0;
}

Output:
Super class function
Sub class function

::::::::Compile time Polymorphism:::::::::

The polymorphism which is implemented at the compile time is known as compile-time polymorphism. Method overloading is an example of compile-time polymorphism.

Method overloading: Method overloading is a technique which allows you to have more than one function with the same function name but with different functionality.

#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;
    cout<<"output:"<<obj.sum(10,20)<<endl;
    cout<<"output:"<<obj.sum(10,20,30)<<endl;
 return 0;

}

No comments:

Post a Comment