3

I have the following classes, and I'm trying to access a base member using an object of class H, and I get an H::a is ambiguous warning.

class E {
public:
    E() : a(11) { }
    int a;
};

class F : public E {
public:
    F() : b(22) { }
    int b;
};

class G : public E {
public:
    G() : c(33) { }
    int c;
};

class H: public F, public G {
public:
    H() : d(44) { }
    int d;
};

I tried making the data member a static, but then it doesn't let me initialize it in the base constructor. What's a solution to these two problems?

Jeffmagma
  • 452
  • 2
  • 8
  • 20
GelatinFox
  • 353
  • 3
  • 6
  • 10

1 Answers1

3

Class "H" has two variables called "a", one derived from F and one from G. You can either use a qualifier,

H::a

or you can use the "virtual" inheritance specifier (see https://stackoverflow.com/a/419999/257645)

#include <iostream>

struct A {
    int a;
};

struct B : virtual public A {
};

struct C : virtual public A {
};

struct D : virtual public B, virtual public C {
    void d1() { a = 1; }
    void d2() { a = 2; }
};

int main() {
    D d;
    d.d1();
    d.d2();
    std::cout << d.a << std::endl;
}

http://ideone.com/p3LPe0

Community
  • 1
  • 1
kfsone
  • 23,617
  • 2
  • 42
  • 74
  • In the OP's code, they're not functions; they're member a variables. – WhozCraig Nov 01 '13 at 04:57
  • Yeah, I was going to demonstrate both and got lazy - changed them to variables just to be consistent with his post. – kfsone Nov 01 '13 at 05:00
  • +1 the premise is right. for an example of how to invoke virtual base class initialization from the point of concentrating the bases, [see this link](http://ideone.com/RPMqYO), and note particularly the seemingly *missing* initializer invocation of the A constructor from the B and C subclasses when constructing D. – WhozCraig Nov 01 '13 at 05:13