What is virtual function in C++?
In this C++ interview questions we will learn about:
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.
Would you like to see your article here on tutorialsinhand.
Join
Write4Us program by tutorialsinhand.com
About the Author
Page Views :
Published Date :
Feb 01,2021