Answer to Question #186277 in C++ for Deepanshi singh

Question #186277

Explain the type of polymorphism with code.


1
Expert's answer
2021-04-27T09:38:34-0400
/*
C++ Supports two main types of polymorphism. Runtime and compile time polymorphism.
Compile time can be accomplished using:
    -Method overloading and
    -Operator overloading.
    in this example we are going to use method overloading.
Runtime polymorphism can be implemented using:
    -Method overriding and
    -Virtual functions
    in this example we will use method overriding to demonstrate


*/
#include <iostream>


using namespace std;


//Compile time polymorphism
class CompileTime
{
    public:
        void display(int x)
        {
            cout<<"The int is : "<<x<<endl;
        }
        void display( char ch)
        {
            cout<<"The character is : "<<ch<<endl;
        }
};


//Runtime polymorphism section
class RuntimeParent
{
    public:
        void sayHello()
        {
            cout<<"Hello from parent"<<endl;
        }
};
class RuntimeChild: public RuntimeParent
{
    public:
        void sayHello() //Method with same name as parent method. This has been overridden.
        {
            cout<<"Hello from child"<<endl;
        }


};


int main()
{
    //Compile time polymorphism using method overloading
    CompileTime ct;
    ct.display(5);
    ct.display('x');


    //Runtime polymorphism using method overriding
    RuntimeChild rc;
    rc.sayHello(); //This will call child class sayHello()


    return 0;
}



Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS