Skip to content
Related Articles

Related Articles

What happens when a virtual function is called inside a non-virtual function in C++
  • Difficulty Level : Hard
  • Last Updated : 20 Dec, 2018
GeeksforGeeks - Summer Carnival Banner

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.

Want to learn from the best curated videos and practice problems, check out the C++ Foundation Course for Basic to Advanced C++ and C++ STL Course for foundation plus STL.  To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.



My Personal Notes arrow_drop_up
Recommended Articles
Page :