virtual inheritance / dreaded diamond problem

Discussion in 'C++' started by Alexander Stippler, Jul 14, 2003.

  1. 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
     
    Alexander Stippler, Jul 14, 2003
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Alexander Stippler

    virtual inheritance / dreaded diamond again

    Alexander Stippler, Aug 26, 2003, in forum: C++
    Replies:
    1
    Views:
    389
    Ron Natalie
    Aug 26, 2003
  2. Tom
    Replies:
    3
    Views:
    502
  3. John Perks and Sarah Mount

    MRO problems with diamond inheritance?

    John Perks and Sarah Mount, May 1, 2005, in forum: Python
    Replies:
    13
    Views:
    600
    Michele Simionato
    May 3, 2005
  4. Alex Hunsley
    Replies:
    4
    Views:
    368
    Colin J. Williams
    Nov 2, 2005
  5. thomas
    Replies:
    5
    Views:
    602
    Gert-Jan de Vos
    Nov 27, 2009
Loading...

Share This Page