1

In this simple class hierarchy I'm trying to get class C to disambiguate which x to use by telling it "using B::x" but this doesn't compile in G++ because it still can't figure out which x I mean in the function foo. I know using can be used to promote hidden methods but why not variables? I've considered making a class X as a virtual base of A and B with a definition for X but that's not strictly what I want; what I want is A:x used by stuff directly derived from it except when derived from B also, sort of like the way Python does it with its member (name) resolution order algorithm (last class wins, so in this case B:x is used, see http://starship.python.net/crew/timehorse/BFS_vs_MRO.html for a description.)

Am I correct in the assessment that ISO C++ 2011 is deficient in this respect; that it's impossible to disambiguate base member variables using "using"?

class A {
protected:
    int x;
};

class B {
protected:
    int x;
};

class C : public A, public B {
protected:
    using B::x;

public:
    int foo(void) { return x; }
};

EDIT: Compiler version: g++ (Ubuntu/Linaro 4.6.3-1ubuntu5) 4.6.3

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
TimeHorse
  • 510
  • 3
  • 14
  • You can say `return B::x;`. I wouldn't call this deficient, it's much less typing than `using B::x`. :) – jrok Feb 27 '13 at 17:34
  • Your code compiles for me: [demonstration](http://ideone.com/nrU8me). `using` applies to names, so should work exactly the same for functions, variables, types, or anything else with a name. Or have I misunderstood the question? – Mike Seymour Feb 27 '13 at 17:41
  • Thanks jrok; the problem with that though is I've not include the entire complexity of the full class hierarchy such that A and B have virtual functions C must provide and the use of x in derived classes is numerous so that's a lot of replacements. Mike, which version of compiler are you using? It doesn't work on g++ 4.6.3 as noted above; which is the latest version to which I have access. – TimeHorse Feb 27 '13 at 18:10

1 Answers1

0

It works fine with C++11 and g++ 4.8 : http://ideone.com/oF4ozq

#include <iostream>
using namespace std;
class A {
protected:
    int x = 5 ;
};

class B {
protected:
    int x = 42 ;
};

class C : public A, public B {
protected:
    using B::x;

public:
    int foo(void) { return x; }
    int fooa(void) { return A::x; }
     int foob(void) { return B::x; }
};
int main() {
    C c;
    std::cout<<c.foo()<<std::endl;
    std::cout<<c.fooa()<<std::endl;
    std::cout<<c.foob()<<std::endl;
    return 0;
}
Davidbrcz
  • 2,335
  • 18
  • 27