
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Virtual Function Called Inside Non-Virtual Function in C++
In this section we will discuss about interesting facts about virtual classes in C++. We will see two cases first, then we will analyze the fact.
At first execute the program without using any virtual function.
The execute the program using any virtual function under non-virtual function.
Example
Let us see the following implementation to get better understanding −
#include <iostream> using namespace std; class BaseClass { public: void display(){ cout << "Print function from the base class" << endl; } void call_disp(){ cout << "Calling display() from derived" << endl; this -> display(); } }; class DerivedClass: public BaseClass { public: void display() { cout << "Print function from the derived class" << endl; } void call_disp() { cout << "Calling display() from derived" << endl ; this -> display(); } }; int main() { BaseClass *bp = new DerivedClass; bp->call_disp(); }
Output
Calling display() from base class Print function from the base class
From the output, we can understand the polymorphic behavior works even when a virtual function is called inside a non-virtual function. Which function will be called is decided at runtime applying the vptr and vtable.
vtable − This is a table of function pointers, maintained per class.
vptr − This is a pointer to vtable, maintained per object instance.
Advertisements