polymorphism c++ code example

Example 1: polymorphism-program.cpp

#include <iostream>

using namespace std;

class Person{
public:
    virtual void introduce(){
    cout <<"hey from person"<<endl;
    }
};

class Student : public Person{
public:
    void introduce(){
    cout <<"hey from student"<<endl;
    }
};

class Farmer : public Person{
public:
    void introduce(){
    cout <<"hey from Farmer"<<endl;
    }
};

void whosThis(Person &p){
p.introduce();
}

int main()
{
    Farmer anil;
    Student alex;

    whosThis(anil);
    whosThis(alex);
    return 0;
}

Example 2: what is polymorphism

The word polymorphism means having many forms. In simple words, we can define polymorphism as the ability of a message to be displayed in more than one form. Real life example of polymorphism: A person at the same time can have different characteristic. Like a man at the same time is a father, a husband, an employee.

Tags: