Open In App

How to Call a Virtual Function From a Derived Class in C++?

In C++, virtual functions play an important role because they allow the users to perform run-time polymorphism. While dealing with inheritance and virtual functions, it is very crucial to understand how to call a virtual function from a derived class. In this article, we will learn how to call a virtual function from a derived class in C++.

Call a Virtual Function From a Derived Class in C++

A virtual function is a member function that is defined in a base class which is later overridden in a derived class. When we call a virtual function through a base class pointer or reference the current most derived class function which will be executed is determined during the runtime of the program.

We can call the base class virtual function by using the scope resolution operator and class name.

BaseClassName::function_name(args);

C++ program to Call a Virtual Function From a Derived Class

The following program demonstrates how we can call a virtual function from a derived class in C++:

// C++ program to Call a Virtual Function From a Derived Class

#include <iostream>
using namespace std;
// Base class
class Base {
public:
    
    // Declaring the virtual function
    virtual void display() {
        cout << "Base class virtual function called" << endl;
    }
};

// Derived class
class Derived : public Base {
public:
    // override the base class virtual function
    void display() override {
        cout << "Derived class function called" << endl;
    }
    
    // Function to call the virtual function from the derived class
    void call() {
        
        // Calling the virtual function from the derived class
        Base::display();
    }
};

int main() {
    // Declare an object of the derived class
    Derived derivedObj;
    
    // Call Derived class display()
    derivedObj.display();
    
    // Call Base class virtual function from Derived class
    derivedObj.call();

    return 0;
}

Output
Derived class function called
Base class virtual function called

Time Complexity:O(1)
Auxiliary Space: O(1)

Article Tags :