tags:

views:

140

answers:

6

hello, in c++ you can put a member in a base class and a member with the same name in the inherited class.

how can i access a specific one in the inherited class?

thanks!

+11  A: 

In that case you should fully qualify a member name.

class A
{
public:
  int x;
};


class B : public A
{
public:
  int x;
  B() 
  { 
    x = 0;
    A::x = 1;
  }
};
Kirill V. Lyadvinsky
+2  A: 

By prefixing it with classname::.

sbi
+5  A: 

If you specify the name you'll access the one in the inherited class automatically. If you mean how do you access the one in the base class, use Base::member

Michael Mrozek
+3  A: 

Yes.

Qualify your call, f(), with a class name: SpecificClass::f().

Daniel Daranas
+3  A: 

To access the hidden member in the base class you have to prefix the member name with the base class name. See below:

class A
{
protected:
   int i;
};

class B : public A
{
public:
   void foo( void )
   {
      int a_i = A::i;
      int b_i = i;
      int b_i_as_well = B::i;
   }
private:
   int i;
};
caspin
+2 [i wish] for the example.
Chris Kaminski
+1  A: 

One approach (already mentioned in all other answers) is to use the qualified member name, like Base::member. It can be used in conjunction with explicit access through this pointer, if that's your style: this->Base::member.

Another approach is to perform access through this pointer explicitly converted to the base class type: ((Base *) this)->member.

Of course, the above references to this pointer are made under assumption that you are trying to access the member from within some non-static member function of the class. To access if from "outside", the same tricks can be applied to any other pointer (or reference): some_pointer->Base::member or ((Base *) some_pointer)->member.

For data members these two approaches are equivalent. For member functions they can lead to different results with virtual functions. For this reason, in general, the first approach should be preferred.

AndreyT