Polymorphism in C++

 What is polymorphism?

              Poly means ‘Many’. Polymorphism means having more than one form. This concept makes the function can be used in different situations.

Let us categories the types.

1.Compile time Polymorphism:

              This is a static one, which can be done in the code itself. It occurs in compile time. This can be achieved by two ways.

Let us create the c++ programs as follows.

· Function Overloading:

              In short, same function name can be used for different functionalities and different number of arguments.

This program starts with creating a class with 2 functions with same name. the function big() has two definitions.

First function big() takes two arguments as integer and it finds the biggest among the two numbers.

Second function big() takes three arguments as integer and it identifies the largest number among the three numbers.

Code:

#include <bits/stdc++.h>

using namespace std;

class calculate {

public:

    // create a Function to find greatest among two integers

    void big(int x, int y) {

        if(x>y)

            cout<<x<<"is the bigger number among "<<x<<"," <<y<<endl;

        else

            cout<<y<<"is the bigger number among "<<x<<"," <<y<<endl;

    }

    // create a funtion to find the biggest among three numbers

    void big(int x,int y, int z) {

        if(x>y && x>z)

         cout<<x<<" is the biggest number among "<<x<<","<<y<<","<<z<<endl;

        else if(y>z)

         cout<<y<<" is the biggest number among "<<x<<","<<y<<","<<z<<endl;

        else

         cout<<z<<"is the biggest number among "<<x<<","<<y<<","<<z<<endl;

       }

};

int main() {

    calculate cc;

    // function call of big() with 2 arguments

    cc.big(100, 12);

    //  function call of big() with 2 arguments

    cc.big(45,56,34);

    return 0;

}

Output:

100is the bigger number among 100,12

56 is the biggest number among 45,56,34

This is the way of creating compile time polymorphism program in C++. Hope, this code is useful to you. Next blog post contains operator overloading and runtime polymorphism.

Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

How to write your first XML program?

Java NIO examples to illustrate channels and buffers.