* Phlip:[color=blue]
> Rolf Magnus wrote:
>[color=green]
>>
vaividhya@gmail.com wrote:
>>[color=darkred]
>>> We can have virtual destructors.Why we can't have virtual constructors?[/color]
>> Because for virtual functions (including the destructor), the system
>> determins the dynamic type of the object to find out which function to
>> call at runtime. But a constructor is called to create the object, so
>> there is no dynamic type to find out yet.[/color]
>
> That's not "why", it just states what the current mechanism is.[/color]
Right you are, so far.
In at least one situation the C++ abstract machine is capable of finding
a relevant static function based on an object's dynamic type (namely, a
deallocation function, 'operator delete'), and in like manner the
language could technically have supported virtual constructors, either
with some run-time checking of argument types, or corresponding checking
of an assumed signature against the actual dynamically found signature,
or simply requiring some fixed, generic signature.
[color=blue]
> The compiler always knows the type of the fully-formed object at
> construction time. So C++ could have been defined as constructing the
> complete virtual method jump table first, instead of last. Then
> constructors could freely call virtual methods into the derived classes,
> and the result would be virtual construction.[/color]
In one sense of "virtual construction", yes: that's the way it works in
Java and C#.
But this is something very different from calling a constructor virtually.
Instead, it's all about virtual calls from a constructor.
[color=blue]
> The reason we can't upgrade the current language to support that feature is
> too much code depends on constructors calling virtual methods that don't
> dispatch to their derived overrides.[/color]
No, the reason that we can't downgrade to the Java/C# model is that we
want to preserve type safety, where type safety includes the notion of
class invariants; see the FAQ at <url:
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.5>.
The reason why we, in practice, can't upgrade C++ to directly support
virtual constructors, virtual calls of constructors, is that this would
extend the language a great deal for something that can easily be
achieved within the language as-is, namely via clone functions.
For those who are not familiar with clone functions, see the FAQ, <url:
http://www.parashift.com/c++-faq-lite/virtual-functions.html#faq-20.8>.
[color=blue]
> The work-around might be "Coplien's Curiously Recurring Template Pattern".[/color]
That's one of several work-arounds for implementing something akin to
the Java/C# model; see the FAQ at <url:
http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.6>.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?