C++ Program to demonstrate virtual function working

This program demonstrates virtual function in c++. When there exist two functions with same function name in both base and derived class the compiler identifies which function to use at run time based on the type of object pointed to by base pointer. The run time polymorphism in c++ is achieved through virtual functions.

Program


 //Run time polymorphism

#include<iostream.h>

#include<conio.h>

class base

{

public:

void display()

{

cout<<"\nDisplay Base";

}

virtual void show()

{

cout<<"\nShow Base";

}

};

class derived:public base

{

public:

void display()

{

cout<<"\nDisplay Derived";

}

void show()

{

cout<<"\nShow Derived";

}

};

void main()

{

base *bptr;

base b;

bptr=&b;

bptr->display();

bptr->show();

derived d;

bptr=&d;

bptr->display();

bptr->show();

getch();

}


Output



Display Base
Show Base
Display Base
Show Derived

No comments: