- 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
How to call a virtual function inside constructors in C++?
Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. This is because the virtual function you call is called from the Base class and not the derived class.
In C++ every class builds its version of the virtual method table prior to entering its own construction. So a call to the virtual method in the constructor will call the Base class' virtual method. Or if it has no implementation at that level, it'll produce a pure virtual method call. Once the Base is fully constructed, the compiler starts building Derived class, and overrides the method pointers to point Derived class' implementation. So for example, If you have the code −
Example
#include<iostream> using namespace std; class Base { public: Base() { f(); } virtual void f() { std::cout << "Base" << std::endl; } }; class Derived : public Base { public: Derived() : Base() {} virtual void f() { std::cout << "Derived" << std::endl; } }; int main() { Derived d; return 0; }
Output
This will give the output −
Base
- Related Articles
- Calling virtual functions inside constructors in C++
- How to call a Java function inside JavaScript Function?
- What happens when a virtual function is called inside a non-virtual function in C++
- How to call a controller function inside a view in Laravel 5?
- How to call a function inside a jQuery plugin from outside?
- Difference between a virtual function and a pure virtual function in C++
- How to call a JavaScript function from C++?
- How to Call a Lua function from C?
- Virtual Function in C++
- How to call a function in JavaScript?
- How to call a parent class function from derived class function in C++?
- How to call the main function in C program?
- How to call promise inside another promise in JavaScript?
- A C/C++ Function Call Puzzle?
- How to call a JavaScript function in HTML?

Advertisements