Q:

C++ program - Polymorphism implementation using Virtual functions.

0

C++ program - Polymorphism implementation using Virtual functions.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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

 

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now