9.
Virtual function in C++
A virtual function is a member function in the base class that we expect to redefine in derived
classes.
A virtual function (also known as virtual methods) is a member function that is declared within a
base class and is re-defined (overridden) by a derived class. When you refer to a derived class
object using a pointer or a reference to the base class, you can call a virtual function for that
object and execute the derived class’s version of the method.
Virtual functions ensure that the correct function is called for an object, regardless of the type of
reference (or pointer) used for the function call.
They are mainly used to achieve Runtime polymorphism.
Functions are declared with a virtual keyword in a base class.
The resolving of a function call is done at runtime.
Example 1: C++ Virtual Function
#include <iostream>
using namespace std;
class Parent {
public:
virtual void print() {
cout << "It is a parent Function" << endl;
}
};
class Child : public Parent {
public:
void print() {
cout << "It is a child Function" << endl;
}
};
int main() {
Child child1;
Parent* parent1 = &child1;
parent1->print();
return 0;
}
Output:
It is a child Function.
Example 2: C++ Virtual Function
#include <iosream>
using namespace std;
class DotNetTricks {
public:
virtual void print() {
cout << "Welcome to DotNetTricks" << endl;
}
void show() {
cout << "This is the base class" << endl;
}
};
class ScholarHat : public DotNetTricks {
public:
void print() {
cout << "Welcome to ScholarHat" << endl;
}
void show() {
cout << "This is the child/derived class" << endl;
}
};
int main() {
ScholarHat sobj1;
// Pointer of the base class type that points to sobj1
DotNetTricks* ptr = &sobj1;
// Virtual function, binded at runtime
ptr->print();
// Non-virtual function, binded at compile time
ptr->show();
return 0;
}
Output
Welcome to ScholarHat
This is the base class