A virtual function is a function that is declared as virtual in a base class. A virtual function is always preceded by the keyword virtual. Virtual functions employ late binding by allocating memory space during execution time and not during compilation time. In this case when a pointer of the base class is defined in a main() function and derived class object's address is passed on to the base class pointer, then calling the overridden function will invoke the derived class member function and not the base class member function as mentioned earlier. Following is a program to illustrate the use of virtual functions.
In this example also there is a base class consumer and a derived class transaction. Both have overridden member functions getdata() and display(). Member data are the same as discussed in the earlier example. The functions in the base class have been declared virtual.
const int size=10;
strcpy(name, " ");
strcpy(tel, " ");
virtual void getdata()
cout<<"Enter Name : ";
cout<<"Enter Code : ";
cout<<"Enter Telephone Number ";
virtual void display()
cout<<"Name : "<<name<<endl;
cout<<"Code : "<<code<<endl;
cout<<"Telephone : "<<tel<<endl;
class transaction: public consumer
cout<<"Enter Quantity : ";cin>>qty;
cout<<"Enter Price : ";cin>>price;
cout<<"Quantity : "<<qty<<endl;
cout<<"Price : "<<price<<endl;
cout<<"Total Price : "<<qty*price<<endl;
It is observed that when the address of the derived class object o2 is passed on to the base class pointer o1 and the base class pointer o1 is used to invoke the overridden member functions getdata() and display(), the derived class member functions are invoked.