the diamond problem

T

Tony Johansson

Hello Experts!

It it correct to say that a solution to the diamond problem is to use
virtual inheritance with virtual base classes.

//Tony
 
P

Pete Becker

Tony said:
It it correct to say that a solution to the diamond problem is to use
virtual inheritance with virtual base classes.

It depends on what you mean by "the diamond problem." You use a virtual
base when you need a base object that's shared among various derived
objects. You don't use a virtual base when you don't want that.
 
J

Jaspreet

Tony said:
Hello Experts!

It it correct to say that a solution to the diamond problem is to use
virtual inheritance with virtual base classes.

//Tony

Yeah, that is one of the most popular and efficient solutions to the
diamond problem.

class base
{
--
};


class der1:public base
{
--
};

class der2:public base
{
--
}

class sub_der:public der1, der2
{
--
}

Soo, now sub_der would have 2 copies of base, one from der1's side and
the other from der2's side. To prevent this we can have the base class
derived virtually.

Just to add, a point which is OT here but in Java, this situation never
arises since it does not support multiple inheritance. But again this
point I said above is completely off-topic.
 
J

Josh Mcfarlane

Jaspreet said:
Just to add, a point which is OT here but in Java, this situation never
arises since it does not support multiple inheritance. But again this
point I said above is completely off-topic.

Well, it could also be argued that this should not occur in C++ if you
design your classes in a way that does not require it, but that's
another day, another thread.
 
P

Pete Becker

Jaspreet said:
Soo, now sub_der would have 2 copies of base, one from der1's side and
the other from der2's side. To prevent this we can have the base class
derived virtually.

And just to clarify: having 2 copies of base is not a "problem" in
itself. It's a problem if it isn't what you want.
 
G

GrahamJWalsh

and just to add, using virtual inheritance impacts the order of
construction of your objects. It's a good interview question tied in
with general questions about order of construction. Basically virtually
inherited classes take precedence before non-virtually inherited
classes. that's just FYI and one to watch if your interviewing. you
can find out more in scott meyers effective c++ and various other
books.


G
 

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,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top