Virtual Function in C++

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.


 Live Demo

#include <iostream>
using namespace std;
class base {
   virtual void print(){
      cout << "print base class" << endl;
   void show(){
      cout << "show base class" << endl;
class derived : public base {
   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
   //calling non-virtual function


print derived class
show base class

Updated on: 12-Mar-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started