Articles

What is virtual function in C++?

What is virtual function in C++?


In this  C++ interview questions we will learn about:

  • what is virtual function in c++?

  • rules for virtual function in c++
  • example of virtual function in c++

What is Virtual Function in C++?

  • A virtual function in c++ is the member function of the base class and it modified in the derived class with having the keyword virtual.
  • Virtual function in c++ is used for the purpose of late binding or dynamic linkage (function call resolved during runtime).
  • It is good to have one pointer for all the classes(base/derived) in a program, but if the base class pointer has a derived class object, it will call the base class function, instead of the derived class function. That is the problem and the solution is 'virtual' function. Virtual function tells the compiler which function to invoke at runtime.

Rules for virtual function in c++

  • Virtual function can't be a static member.
  • It can be accessed through pointers.
  • The virtual function can be friend to another class.

Example of virtual function in c++

Given below is an example of virtual function in C++

#include <iostream>
using namespace std;

class A {
   public:
    virtual void dis() {
cout << "Base Fn." ;
cout<<endl;
    }
};

class B : public A {
   public:
    void dis() {
 cout << "Derived Fn.";
cout<<endl;
    }
};

int main() {
    A* a; // pointer of base class
    B b;  // object of derived class


     a = &b;

    // late binding 
    a->dis();

    return 0;
}

Output

Derived Fn.

 

Working:

dis() function of class B is called as dis() function of class is virtual.

 

 

 


cpp interview questions

Would you like to see your article here on tutorialsinhand. Join Write4Us program by tutorialsinhand.com

About the Author
Subhajit Guha Thakurta
Page Views :    Published Date : Feb 01,2021  
Please Share this page

Related Articles

Like every other website we use cookies. By using our site you acknowledge that you have read and understand our Cookie Policy, Privacy Policy, and our Terms of Service. Learn more Got it!