Search code examples
c++multiple-inheritanceobjective-c++

How to resolve ambiguous variables names inherited multiple times?


so I have a following problem. I have a class which is a subclass of two other classes and they both have positions. Like in this example:

struct A
{
    float x, y;
    std::string name;

    void move(float x, float y)
    {
        this->x += x;
        this->y += y;
    }
};

struct B
{
    float x, y;
    int rows, columns;

    void move(float x, float y)
    {
        this->x += x;
        this->y += y;
    }
};

struct C : public A, public B
{
    void move(float x, float y)
    {
        this->x += x; //generates error: "C::x is ambiguous
        this->y += y; //generates error: "C::y is ambiguous
    }
};

Later in the code I refer to class C both as an A class and a B class and when I get the position I have a problem. Can I somehow "combine" position variables of both classes? And if not can I change positions of both classes at the same time or do I have to do it like this:

void move(float x, float y)
{
    this->x1 += x;
    this->y2 += y;
    this->x1 += x;
    this->y2 += y;  
}

Thanks in advance!


Solution

  • In C++, this can be disambiguated by prefixing the member variable with its class scope:

    struct C : public A, public B
    {
      void move(float x, float y)
      {
        A::x += x;
        A::y += y;
        B::x += x;
        B::y += y;  
      }
    };