
- C++ Basics
- C++ Home
- C++ Overview
- C++ Environment Setup
- C++ Basic Syntax
- C++ Comments
- C++ Data Types
- C++ Variable Types
- C++ Variable Scope
- C++ Constants/Literals
- C++ Modifier Types
- C++ Storage Classes
- C++ Operators
- C++ Loop Types
- C++ Decision Making
- C++ Functions
- C++ Numbers
- C++ Arrays
- C++ Strings
- C++ Pointers
- C++ References
- C++ Date & Time
- C++ Basic Input/Output
- C++ Data Structures
- C++ Object Oriented
- C++ Classes & Objects
- C++ Inheritance
- C++ Overloading
- C++ Polymorphism
- C++ Abstraction
- C++ Encapsulation
- C++ Interfaces
What happens when a virtual function is called inside a 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.
- Related Articles
- Difference between a virtual function and a pure virtual function in C++
- How to call a virtual function inside constructors in C++?
- What happens when a function is called before its declaration in C?
- Virtual Function in C++
- Inline virtual function in C++
- Difference Between Virtual and Pure Virtual Function
- Why is a C++ pure virtual function initialized by 0?
- Default arguments and virtual function in C++
- Calling virtual functions inside constructors in C++
- C++ interview questions on virtual function and abstract class
- What is a virtual base class in C++?
- What is a virtual image? Give one situation where a virtual image is formed.
- When to use virtual destructors in C++?
- What is a Virtual Circuit Identifier (VCID)?
- What is Virtual LAN?

Advertisements