You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
In the context of programming, polymorphism allows you to refer to objects of different classes by means of the same program item and to perform the same operation in different ways, depending on which object is being referred to.
In C++, one way polymorphism is implemented is through the use of virtual functions.
When virtual functions are used, the system makes the decision of which method to actually call based on which object the pointer is pointing to.
The decision of which function to call is not made during the time when the code is compiled but when the code is executed.
This is dynamic binding and can be very useful in some programming situations.
In the program below we will see how virtual functions are used.
We will use a protected data member in the base class and publicly derive two classes from the base class.
The base class will have a virtual member function that is redefined in the derived classes.
*/
#include<iostream>
usingnamespacestd;
classPerson
{
protected:
constchar* name;
public:
Person(string n)
{
name=n.c_str();
}
virtualvoidprint()
{
cout << "My name is " << name << endl;
}
};
classForeigner:publicPerson
{
public:
Foreigner(string f):Person(f){}
voidprint()
{
cout << "IL mio nome e " << name << endl;
}
};
classAlien:publicPerson
{
public:
Alien(string s):Person(s){}
voidprint()
{
cout << "##$&(<@$%@!#@$%~~***@## " << name << endl;
cout << "Sorry, there is a communication problem" << endl;