
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
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
Advertisements