Open In App
Related Articles

Virtual Functions in Derived Classes in C++

Improve Article
Improve
Save Article
Save
Like Article
Like

A virtual function is a member function of a base class that is overridden by a derived class. When you use a pointer or a reference to the base class to refer to a derived class object, you can call a virtual function for that object and have it run the derived class’s version of the function.

In C++, once a member function is declared as a virtual function in a base class, it becomes virtual in every class derived from that base class. In other words, it is not necessary to use the keyword virtual in the derived class while declaring redefined versions of the virtual base class function.

For example, the following program prints “C::fun() called as “B::fun() becomes virtual automatically.

CPP




// C++ Program to demonstrate Virtual
// functions in derived classes
#include <iostream>
using namespace std;
 
class A {
public:
    virtual void fun() { cout << "\n A::fun() called "; }
};
 
class B : public A {
public:
    void fun() { cout << "\n B::fun() called "; }
};
 
class C : public B {
public:
    void fun() { cout << "\n C::fun() called "; }
};
 
int main()
{
    // An object of class C
    C c;
   
    // A pointer of class B pointing
    // to memory location of c
    B* b = &c;
   
    // this line prints "C::fun() called"
    b->fun();
   
    getchar(); // to get the next character
    return 0;
}


Output

 C::fun() called 

Note: Never call a virtual function from a CONSTRUCTOR or DESTRUCTOR

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 16 May, 2022
Like Article
Save Article
Previous
Next
Similar Reads