![]() |
|
![]() |
|
|
Thread Tools | Display Modes |
|
|
#1 |
|
Newbie
Join Date: Sep 2005
Posts: 2
Rep Power: 0
![]() |
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.. |
|
|
|
|
|
#2 |
|
Programming Guru
![]() Join Date: Aug 2005
Location: England
Posts: 1,499
Rep Power: 4
![]() |
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. |
|
|
|
|
|
#3 |
|
Resident Grouch
![]() ![]() ![]() ![]() ![]() ![]() Join Date: Jun 2005
Posts: 6,453
Rep Power: 10
![]() |
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?
__________________
Abstraction doesn't make it impossible to write bad code; it makes it possible to write superior code. Contributor's Corner: Grumpy on C++ Exceptions DaWei on Pointers |
|
|
|
|
|
#4 |
|
Programming Guru
![]() Join Date: Jun 2005
Location: Adelaide, South Australia
Posts: 1,192
Rep Power: 5
![]() |
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. |
|
|
|
|
|
#5 |
|
Programmer
Join Date: Jun 2005
Posts: 86
Rep Power: 4
![]() |
Here's the reason straight from Mr. Stroustrup himself:
http://www.research.att.com/~bs/bs_f...l#virtual-ctor |
|
|
|
![]() |
| Bookmarks |
| Currently Active Users Viewing This Thread: 1 (0 members and 1 guests) | |
| Thread Tools | |
| Display Modes | |
|
|