virtual base class

Hi All,
as we all know if i have a base class A
and i derive two other classes B and C like this:
class B : public virtual A
{};
class C : public virtual A
{};

then both B and C have the same copy of the object A.

What if i want two such copies of A in spread across 5 different derived classes?

class B : public virtual A //copy 1 reqd
{};
class C : public virtual A //copy 2 reqd
{};
class D : public virtual A //copy 1 reqd
{};
class E : public virtual A //copy 1 reqd
{};
class F : public virtual A //copy 2 reqd
{};

how can i achieve this ??
That is not what virtual inheritance does.

B and C both have separate copies of A.

If D inherited both B and C, then D would have one copy of A, not two.
If B and C both have separate copies of A, how can D have only one copy ? How will D decide which copy it takes , of B or of C ??

The compiler takes care of that for you, because it knows that D has inherited A twice. The compiler generates the appropriate code to set up the vtables correctly.

@jsmith:
this is a code I found in stroustrup

class Componenet : public virtual Storable {/*...*/};
class Receiver : public Component {/*...*/};
class Transmitter : public Component {/*...*/};
class Radio : public Receiver, public Transmitter {/*...*/};

The shape of inheritence I get is

Storable

Component Component

Receiver transmitter

Radio

if what you have written is correct, when i don't declare Radio, I should not be getting the graph like this


Storable

Component Component

Receiver transmitter

Will I or Not ?
Last edited on
Topic archived. No new replies allowed.