
- 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
Why C++ does not have a virtual constructor?
The virtual mechanism works only when we have a base class pointer to a derived class object.
In C++, constructor cannot be virtual, because when constructor of a class is executed there is no virtual table in the memory, means no virtual pointer defined yet. So, the constructor should always be non-virtual.
But virtual destructor is possible. Here is an example
Example
#include<iostream> using namespace std; class b { public: b() { cout<<"Constructing base \n"; } virtual ~b() { cout<<"Destructing base \n"; } }; class d: public b { public: d() { cout<<"Constructing derived \n"; } ~d() { cout<<"Destructing derived \n"; } }; int main(void) { d *derived = new d(); b *bptr = derived; delete bptr; return 0; }
Output
Constructing base Constructing derived Destructing derived Destructing base
- Related Articles
- Why does a laboratory thermometer not have a kink?
- Why does clinical thermometer not have alcohol ?
- Why does our urine does not have any blood cell?
- Why permanent tissues does not have cell division?
- Why the animal cell does not have a cell wall?
- Does a constructor have a return type in Java?
- Why an interface doesn't have a constructor whereas an abstract class have a constructor in Java?
- Virtual Constructor in C++
- Virtual Copy Constructor in C++
- Why Light(VIBGYOR) does not have white, brown or black colours?
- A fused bulb does not glow. Why?
- You Have a Cold. Why Does Your Stomach Hurt?
- Why does Lua have no “continue” statement?
- Why light does not travel in a zigzag path?
- Why does earth have its own magnetic fields ?

Advertisements