Construtors

A

amit tikoo

Hi all
I want to know reasons behind why we cannot delcare construtors virtual

Thanks
 
Z

Zara

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
 

Ask a Question

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.

Ask a Question

Members online

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top