Skip to content
Related Articles
Open in App
Not now

Related Articles

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

Improve Article
Save Article
  • Difficulty Level : Medium
  • Last Updated : 20 Dec, 2018
Improve Article
Save Article

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




#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;
}

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.




#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;
}

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
Related Articles

Start Your Coding Journey Now!