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 .
Learn to code easily with our course
Coding for Everyone . This course is accessible and designed for everyone, even if you're new to coding. Start today and join millions on a journey to improve your skills!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!
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
11 Apr, 2023
Like Article
Save Article
Share your thoughts in the comments
Add Your Comment
Please Login to comment...