C++ Virtual Function - Devbhoomi

FREE JOB ALERT & ONLINE TUTORIALS

Hot

Post Top Ad

Sunday 8 October 2017

C++ Virtual Function

C++ Virtual Function


Polymorphism is refers to the property by which objects belonging to different classes are able to respond to the same message but in different forms. When there are C++ functions with same name in both super class as well as sub class, virtual functions gives programmer capability to call member function of different class by a same function call based upon different context. This feature is known as polymorphism which is one of the important features of OOP. Pointer is also one of the key aspects of C++ language similar to that of C. In this chapter we will be dealing with virtual functions and pointers of C++.

What is Virtual Function?

A virtual function is a special form of member function that is declared within a base class and redefined by a derived class. The keyword virtual is used to create virtual function, precede the function’s declaration in the base class. If a class includes a virtual function and if it gets inherited, the virtual class redefines a virtual function to go with its own need. In other words, a virtual function is a function which gets override in the derived class and instructs the C++ compiler for executing late binding on that function. Function call is resolved at run time in late binding and so compiler determines the type of object at run time.

Program for Virtual Function:

Example:
#include 
using namespace std; 

class b
{
public:
 virtual void show()
 {
  cout<<"\n  Showing base class....";
 }
 void display()
 {
  cout<<"\n  Displaying base class...." ;
 }
};

class d:public b
{
public:
 void display()
 {
  cout<<"\n  Displaying derived class....";
 }
 void show()
 {
  cout<<"\n  Showing derived class....";
 }
};

int main()
{
 b B;
 b *ptr;
 cout<<"\n\t P points to base:\n"  ;
 ptr=&B;
 ptr->display();
 ptr->show();
 cout<<"\n\n\t P points to drive:\n";
 d D;
 ptr=&D;
 ptr->display();
 ptr->show();
}
Program Output:
     P points to base:

Displaying base class....
Showing base class....
   
     P points to drive:
      
Displaying base class....
Showing derived class....




No comments:

Post a Comment

Post Top Ad