0

A very simple question but yet confusing:

Why does a using directive change the inheritance!? This compiles with Comeau.

I have read that a using directive (decleration?) makes the variable public, but why? What I want is just a nice method not to write always this->x inside B...?

class A{
protected:
    int x;
public:
};

class B: public A {
public:
    using A::x;
};

int main(){
  B b;
  b.x = 2;
}

Thanks!

Stephane Rolland
  • 38,876
  • 35
  • 121
  • 169
Gabriel
  • 8,990
  • 6
  • 57
  • 101
  • 1
    You don't have to write `this->x` inside B... – Luchian Grigore Jul 17 '12 at 07:47
  • OK , jeah I have templates actually, and I can avoid using this-> by simply adding in the right "section" (private,protected, public) (to not change the inheritance) section a using decleration... thats the way... – Gabriel Jul 18 '12 at 08:18

2 Answers2

2

You are the class designer, you are allowed to make the variable public.

If you don't want that, don't put the using in the public section.

And you don't have to use this->x in the derived class, unless the base class is a template.

Bo Persson
  • 90,663
  • 31
  • 146
  • 203
2

Why does a stupid using directive change the inheritance!?

Because you've declared the using declaration (not directive) public. Make it protected or private if you don't want it to be generally accessible.

What I want is just a nice method not to write always this->x inside B...?

Usually, and in your example, you don't have to. You'll only need to do that if A and B are both templates, and the base class is dependent (i.e. depends on the derived class's template parameters). In that case, a private using will allow you to avoid writing this->x.

Mike Seymour
  • 249,747
  • 28
  • 448
  • 644