virtual inheritance / dreaded diamond problem

A

Alexander Stippler

I've got an inheritance structure with two coupled "dreaded diamonds" like
shown below:
A
/ \
/ \
B C
\ / \
\ / \
D E
\ /
\ /
F

Now I get into some trouble with constructor calls. Default constructors get
called in situations, I would expect other constructors to be called. The
following example shows the problem:

#include <iostream>

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

class B
: public virtual A
{
public:
B() { std::cerr << "B()" << std::endl; }
B(const A &a) { std::cerr << "B(const A& a)" << std::endl; }
};

class C
: public virtual A
{
public:
C() { std::cerr << "C()" << std::endl; }
};

class D
: public B,
public C
{
public:
D() { std::cerr << "D()" << std::endl; }
D(const B &b) : B(b) { std::cerr << "D(const B &b)" << std::endl; }
};

class E
: virtual public C
{
public:
E() { std::cerr << "E()" << std::endl; }
};

class F
: public D,
public E
{
public:
F() { std::cerr << "F()" << std::endl; }
F(const D &d) : D(d) { std::cerr << "F(const D &d)" << std::endl; }
};

int
main()
{
D d;
F f(d);
}

Of course all classes have also data members. What I do not understand is
the sequence of called constructors. Why does the initializer list of the
second constructor of F not call D::D(const B &b). Is it about virtual
inheritance? Where am I wrong. How do I organize a structure like the above
correctly?

regards,
Alex
 

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

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,023
Latest member
websitedesig25

Latest Threads

Top