What happens when a virtual function is called inside a non-virtual function in C++

Predict the output of the following simple C++ program without any virtual function.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
  
class Base
{
public:
    void print()
    {
        cout << "Base class print function \n";
    }
    void invoke()
    {
        cout << "Base class invoke function \n";
        this -> print();
    }
};
  
class Derived: public Base
{
public:
    void print()
    {
        cout << "Derived class print function \n" ;
    }
    void invoke()
    {
        cout << "Derived class invoke function \n";
        this -> print();
    }
};
  
int main()
{
    Base *b = new Derived;
    b -> invoke();
    return 0;
}

chevron_right


Output:

Base class invoke function
Base class print function

Since there is no virtual function, run time polymorphic behavior doesn’t not work in the above code. Now predict the output of the following C++ program.

filter_none

edit
close

play_arrow

link
brightness_4
code

#include <iostream>
using namespace std;
  
class Base
{
public:
    virtual void print()
    {
        cout << "Base class print function \n";
    }
    void invoke()
    {
        cout << "Base class invoke function \n";
        this -> print();
    }
};
  
class Derived: public Base
{
public:
    void print()
    {
        cout << "Derived class print function \n" ;
    }
    void invoke()
    {
        cout << "Derived class invoke function \n";
        this -> print(); // called under non - virtual function
    }
};
  
int main()
{
    Base *b = new Derived;
    b -> invoke();
    return 0;
}

chevron_right


Output:

Base class invoke function
Derived class print function

So polymorphic behaviour works even when a virtual function is called inside a non-virtual function. The output can be guessed from the fact that the function to be called is decided at run-time using the vptr and vtable.

This article is contributed by Sumit Jaiswal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.



My Personal Notes arrow_drop_up

Improved By : xdsarkar



Article Tags :
Practice Tags :


4


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.