virtual inheritance.

R

Radde

Hello,
when i run the below code.. I get output

A()
A()
B()
C()
D()

dont know? why in this sequence?

#include<iostream.h>

class A
{
public:
A()
{
cout<<"A()"<<endl;
}
};

class B: public A
{
public:
B()
{
cout<<"B()"<<endl;
}
};
class C: public virtual A
{
public:
C()
{
cout<<"C()"<<endl;
}
};

class D: public B,public C
{
public:
D()
{
cout<<"D()"<<endl;
}
};

void main()
{
D d;
}

But when i make class B : public virtual A{}
and class C : public A(}

i get output
A()
B()
A()
C()
D()

how is this??

I get same output even if i dont use virtual inheritance(same as
above)..This is agreeable..But i dont know the first one and second
one?? I realy didnt understand the constructor calling mechanism..

Cheers..
 
V

Victor Bazarov

Radde said:
[...initialisation of virtual base subobject seems out of order...]
how is this??

All you need to know is that virtual base subobjects are constructed by
the most derived class' constructor's initialiser list.

V
 
M

Mark P

Radde said:
Hello,
when i run the below code.. I get output

A()
A()
B()
C()
D()

dont know? why in this sequence?

#include<iostream.h>

class A
{
public:
A()
{
cout<<"A()"<<endl;
}
};

class B: public A
{
public:
B()
{
cout<<"B()"<<endl;
}
};
class C: public virtual A
{
public:
C()
{
cout<<"C()"<<endl;
}
};

class D: public B,public C
{
public:
D()
{
cout<<"D()"<<endl;
}
};

void main()
{
D d;
}

Here's my understanding:

First constructed is the virtual A, then D inititiates B and C, and B
initiates A, so A is constructed again, followed by B, then C, and
finally D.
But when i make class B : public virtual A{}
and class C : public A(}

i get output
A()
B()
A()
C()
D()

how is this??

Again, first virtual A, then D initiates B and C, so B is constructed
first then for C we get A and C in that order, and finally D.
I get same output even if i dont use virtual inheritance(same as
above)..This is agreeable..But i dont know the first one and second
one?? I realy didnt understand the constructor calling mechanism..

Cheers..

Basically the virtual constructors are called first and then what's left
over is called in depth-first left-to-right order.
 
L

leonardo77

All you need to know is that you should first read the C++-FAQ-Lite!
:->)) Site:"parashift.com\c++-faq-lite" ,look for virtual inheritance.

Isn't the FAQ supposed to handle cases like this?

_________________________________________________________

leo77

There is nothing new in this universe...
 

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
474,297
Messages
2,571,536
Members
48,284
Latest member
alphabetsalphabets

Latest Threads

Top