Virtual Function in C++

Advertisements

Prev Tutorial Next Tutorial

Virtual Function in C++

A virtual function is a member function of class that is declared within a base class and re-defined in derived class.

When you want to use same function name in both the base and derived class, then the function in base class is declared as virtual by using the virtual keyword and again re-defined this function in derived class without using virtual keyword.

Syntax

	
virtual return_type function_name()
{
 .......
 .......
}

Virtual Function Example

	
#include<iostream.h>
#include<conio.h>

class A
{
public:
 virtual void show()
 {
  cout<<"Hello base class";
 }
};

class B : public A
{
 public:
  void show()
  {
   cout<<"Hello derive class";
 }
};

void main()
{
clrsct();
A aobj;
B bobj;
A *bptr;
bptr=&aobj;
bptr->show();  // call base class function

bptr=&bobj;
bptr->show();  // call derive class function
getch();
}

Output

	
Hello base class
Hello derive class

Prev Tutorial Next Tutorial

Google Advertisment

Buy This Ad Space @$20 per Month, Ad Size 600X200 Contact on: hitesh.xc@gmail.com or 9999595223

Magenet is best Adsense Alternative here we earn $2 for single link, Here we get links ads. Magenet

For Projects 9999595223

Google Advertisements


Buy Websites 9999595223

Buy College Projects with Documentation Contact on whatsapp 9999595223. Contact on: hitesh.xc@gmail.com or 9999595223 Try this Keyword C++ Programs

Advertisements