On 5 Apr 2006 01:42:00 -0700, "amit tikoo" <am*******@gmail.com>
wrote:
Hi all
I want to know reasons behind why we cannot delcare construtors virtual
Well, let's see:
Virtual functions take their value right before constructor is
invoked. So, it seems there would be no problem, as the constructor
would be available when it should be invoked.
But it is not so easy. let's see the following inheritance
supposition, with virtual constructors available:
struct A {
virtual A(int i);
};
struct B:public A {
virtual B(int i);
};
B sample(5);
What happens when trying to construct "sample"?
1.- Memory is allocated, enough for struct B.
2.- Contructor invoked? But which one? B constructor will not be
available until A is fully constructed. So, A will begin to be
constructed, but how? As B constructor is not available, there is
either no way to know how to construct A, or the virtual constructor
available is A constructor and this will be the one called, never
calling B constructor.
So, point 2 reflects the paradox of virtual constructors and why C++
language cannot support them as a secondary effect of the standar
construction order.
That is the reason to use Factory methods for polimorphic creation of
objects.
Best regards,
Zara