In this tutorial, we will be discussing a program to understand virtual functions in C++.
Virtual function is the member function defined in the base class and can further be defined in the child class as well. While calling the derived class, the overwritten function will be called.
Example
#include <iostream>
using namespace std;
class base {
public:
virtual void print(){
cout << "print base class" << endl;
}
void show(){
cout << "show base class" << endl;
}
};
class derived : public base {
public:
void print(){
cout << "print derived class" << endl;
}
void show(){
cout << "show derived class" << endl;
}
};
int main(){
base* bptr;
derived d;
bptr = &d;
//calling virtual function
bptr->print();
//calling non-virtual function
bptr->show();
}Output
print derived class show base class