Polymorphism Through Virtual Functions in OOP

Virtual means existing in appearance but not in reality. A virtual function is a special member function defined in the base class and overridden in one or more derived classes. It means that name of the function and its signature in base and derived classes remains the same.

Polymorphism is achieved through the use of virtual functions.

Here is a Person class with a Student subclass and a Lecturer Subclass.

class Person
{
public:
	Person	(char *s)
	{
		name = new char[strlen(s+1)];
		strcpy(name,s);
	}
	void print()
	{
		cout<<"My name is "<<name<<"\n";
	}
protected:
	char *name;
};
class Student : public Person
{
public:
	Student	(char *s, float g) : Person	(s), gpa(g) {}
	void print()
	{
		cout<<"My Name is "<<name<<" and My GPA is "<<gpa<<"\n";
	}
private:
	float gpa;
};
class Lecturer : public Person	
{
public:
	Lecturer(char *s, int n) : Person(s), publs(n) {}
	void print	()
	{
		cout<<"My Name	is "<<name<<" and I have "<<publs<<" Publications\n";

	}
private:
	int publs;
};
main()
{
	Person	*p;
	Perosn x("Mike");
	p = &x;
	p->print();
	Student	y ("Jack", 3.45);
	p = &y;
	p->print();
	Lecturer z("Selena", 6);
	p = &z;
	p->print();	
}

Output

My name is Mike
My name is Jack
My name is Selena

The print function defined in the base class is not virtual.

So the call p->print() always invokes that same base class function Person::print() because p has type Person*.

The pointer p is statically bound to that base class function at compile time.
Now Change the base class function Person :: print() into virtual function and run the same program .

class Person
{
public:
	Person	(char *s)
	{
		name = new char[strlen(s+1)];
		strcpy(name,s);
	}
	virtual void print()
	{
		cout<<"My name is "<<name<<"\n";
	}
protected:
	char *name;
};

Output

My name is Mike
My name is Jack and my GPA is 3.45
My name is Selena and I have 6 Publications

Now the pointer p is dynamically bound to the print() function of whatever object it points to.

So the first call

p->print() 

invokes the base class function

Person :: print()

and the second call invokes the derived class function

Student :: print()

and the third call invokes the derived class function

Lecturer :: print().

So we can say that the call p->print() is polymorphic because its meaning changes according to circumstances.

Generally, a member function should be declare as virtual whenever it is anticipated that at least some of its subclass will define their own local version of the function

OOP Programming
OOP Programming ,
OOP Programming ,
OOP Programming ,
OOP Programming ,
OOP Programming ,
OOP Programming ,
OOP Programming ,
OOP Programming ,OOP Programming, OOP Programming,OOP Programming,OOP Programming

Leave a Reply