What happens when a virtual function is called inside a non-virtual function in C++
Last Updated :
11 Apr, 2023
Predict the output of the following simple C++ program without any virtual function.
CPP
#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 work in the above code. Now predict the output of the following C++ program.
CPP
#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();
}
};
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 .
Like Article
Suggest improvement
Share your thoughts in the comments
Add Your Comment
Please Login to comment...