Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   C++ (http://www.programmingforums.org/forum15.html)
-   -   Why can't we have Virtual Constructors??? (http://www.programmingforums.org/showthread.php?t=5994)

kaustubhkane Sep 21st, 2005 4:22 AM

Why can't we have Virtual Constructors???
 
Hi All,

While using the concept of Polymorphism in C++ we use Virtual Destructors. These are normally used when we maintain a common list (normally array of pointers of type Base Class) and each element in this array can point to the derived class... for e.g:

Base* ptr[i] = new Derived;

While destroying the objects we use Virtual destructors.

In the same way why cant we have Virtual Constructors???

Eagerly waiting 4 the reply...

Thanks..

Arevos Sep 21st, 2005 6:29 AM

It's been a while since I've programmed in C++, but as I understand it, the difference between virtual and non-virtual functions is that non-virtual functions are chosen dependant on the casted type of an object, whereas virtual fuctions are chosen dependant on the internal type of an object.

So without the virtual keyword, the command "((Animal)dog).speak()" will call a different function from "dog.speak()".

Because of this, there is no such thing as a virtual constructor, because a constructor cannot be cast, because the object hasn't been created yet. So a virtual constructor makes no sense.

DaWei Sep 21st, 2005 6:33 AM

One way of looking at it is that a virtual destructor destroys the most heavily derived object. Exactly how are you going to map that action to construction?

grumpy Sep 21st, 2005 7:49 AM

The actual reason is that the choice of calling a virtual function is based on the actual type of an object. The order of construction (base classes constructors are invoked before derived class constructors) means that the type is not determined until after the most derived constructor is invoked (i.e. after the object is constructed).

The term "virtual constructor", in the sense that you mean it, is therefore actually a contradiction: a member function of a class can either be virtual or it can be a constructor. It cannot be both.

Scorpions4ever Sep 21st, 2005 9:21 AM

Here's the reason straight from Mr. Stroustrup himself:
http://www.research.att.com/~bs/bs_f...l#virtual-ctor


All times are GMT -5. The time now is 4:30 PM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC