V
vaividhya
We can have virtual destructors.Why we can't have virtual constructors?
We can have virtual destructors.Why we can't have virtual constructors?
We can have virtual destructors.Why we can't have virtual constructors?
Rolf said: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.
That's not "why", it just states what the current mechanism is.
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.
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.
The work-around might be "Coplien's Curiously Recurring Template Pattern".
Alf said:But this is something very different from calling a constructor virtually.
Instead, it's all about virtual calls from a constructor.
Want to reply to this thread or ask your own question?
You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.