C C++ Java Data Structure Python JavaScript CSS Ajax PL/SQL PHP Puzzles C programs C++ programs Java programs

Code Snippets C/C++ Code Snippets

C++ program - Polymorphism implementation using Virtual functions.

By: IncludeHelp, On 09 OCT 2016






In this program we will learn how to implement polymorphism with inheritance using virtual functions in c++ programming language?

If there are same member functions in Base and Derived classes, the objects of derived classes will call member function of Base class.

Let’s see the example (without using virtual functions)

Let’s consider the following example:

#include <iostream>

using namespace std;

class Base{
	public:
		void disp(){
			cout<<"disp function of Base class"<<endl;
		}
};
class Derived1: public Base{
    public:
		void disp(){
			cout<<"disp function of Derived1 class"<<endl;
		}	
};
class Derived2: public Base{
    public:
		void disp(){
			cout<<"disp function of Derived2 class"<<endl;
		}	
};
int main(){
	
	Base *b;
	Derived1 D1;
	Derived2 D2;
	
	b= &D1;
	b->disp();
	
	b= &D2;
	b->disp();
	
	return 0;
}

Output

    disp function of Base class
    disp function of Base class

C++ program (Code Snippet) – Implementation of Polymorphism using Virtual Functions

How to access derived class’s functions (using virtual function)?

There are three things, you have to do implement a polymorphism using virtual member functions, and the steps are:

  • Use virtual keyword with Base class’s member function
  • Create a pointer of Base class, assign address of Derived class’s member function
  • Call member functions with the Base class’s pointer

Let’s consider the following example:

#include <iostream>

using namespace std;

class Base{
	public:
		virtual void disp(){
			cout<<"disp function of Base class"<<endl;
		}
};
class Derived1: public Base{
    public:
		void disp(){
			cout<<"disp function of Derived1 class"<<endl;
		}	
};
class Derived2: public Base{
    public:
		void disp(){
			cout<<"disp function of Derived2 class"<<endl;
		}	
};
int main(){
	
	Base *b;
	Derived1 D1;
	Derived2 D2;
	
	b= &D1;
	b->disp();
	
	b= &D2;
	b->disp();
	
	return 0;
}

Output

    disp function of Derived1 class
    disp function of Derived2 class