Search Your Topic

config
Saturday, 17 June 2017 07:29

C++ virtual function

Written by
Rate this item
(0 votes)

C++ virtual function is a member function in base class that you redefine in a derived class. It is declare using the virtual keyword.

It is used to tell the compiler to perform dynamic linkage or late binding on the function.


Late binding or Dynamic linkage

In late binding function call is resolved during runtime. Therefore compiler determines the type of object at runtime, and then binds the function call.


C++ virtual function Example

Let's see the simple example of C++ virtual function used to invoked the derived class in a program.

 
  1. #include <iostream>  
  2. using namespace std;  
  3. class A  
  4. {  
  5.  public:  
  6.  virtual void display()  
  7.  {  
  8.   cout << "Base class is invoked"<<endl;  
  9.  }  
  10. };  
  11. class B:public A  
  12. {  
  13.  public:  
  14.  void display()  
  15.  {  
  16.   cout << "Derived Class is invoked"<<endl;  
  17.  }  
  18. };  
  19. int main()  
  20. {  
  21.  A* a;    //pointer of base class  
  22.  B b;     //object of derived class  
  23.  a = &b;  
  24.  a->display();   //Late Binding occurs  
  25. }  

Output:

Derived Class is invoked  
Read 197 times
Anish Sir

"I am delighted once again to pen the welcome note to the Tosh!Yas Technologies ."

 Call +91 74 88 34 7779  | Email : anishsingh@live.com

toshiyas.in

Leave a comment

Make sure you enter all the required information, indicated by an asterisk (*). HTML code is not allowed.