- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calling virtual functions inside constructors in C++
Virtual functions calling from a constructor or destructor is dangerous and should be avoided whenever possible as the virtual function we call is called from the Base class and not from the derived class.
The reason is that in C++ Super-classes are constructed before derived classes. So, in the following example, as B must be instantiated, before D is instantiated. When B's constructor is called, it's not D yet, so the virtual function table still has the entry for B's copy of s().
Example Code
#include<iostream> using namespace std; class B { public: B() { s(); } virtual void s() { cout << "Base" << endl; } }; class D: public B { public: D() : B() {} virtual void s() { cout << "Derived" <<endl; } }; int main() { D de; }
Output
Base
- Related Articles
- How to call a virtual function inside constructors in C++?
- What are virtual functions in C#?
- Virtual functions in derived classes in C++
- Virtual Functions and Runtime Polymorphism in C++
- How are virtual functions implemented in C++?
- Pure Virtual Functions and Abstract Classes in C++
- Calling Stored Procedure inside foreach PHP Codeigniter
- Can a C++ virtual functions have default parameters?
- What happens when a virtual function is called inside a non-virtual function in C++
- What are Java methods equivalent to C# virtual functions?
- What is the difference between virtual and abstract functions in C#?
- Constructors in C#
- Constructors in C++
- Write a C program for electing a candidate in Elections by calling functions using Switch case
- Default Constructors in C++

Advertisements