Thursday, March 29, 2012

Virtual constructors in C++!!

When you try to declare a constructor as virtual in C++ and compile, you will get compile time error saying that "error: constructors cannot be declared virtual". This is because in C++, constructors can't be declared as virtual. lets see why?

Virtual functions in C++ are implementation of run time polymorphism. And they will do function overriding.  Generally virtual keyword used in C++ when you need Dynamic behavior. It will work only when object exists.  Where as constructors are used to create the objects. Constructors will be called at the time of object creation.

So if you create the constructor as virtual, as per the virtual keyword definition, it should have existing object to use, but constructor is to creating the object, these two will never exists. So should not use the constructor as virtual.

You can use virtual destructors because, at the time of calling destructor, you have the objects. So you can use virtual keyword for the destructors.

No comments:

Popular Posts