简体   繁体   中英

C++: Hiding members in subclasses. Does it make sense?

I've just came across using-directive in a context, which is new for me - eg "moving" a member of parent class from public to private. I've tested the example below and two question arose:

  1. Is the code at (1) portable? According to standard it should be deprecated.
  2. Does it make sense at all to hide public members in subclasses? (I think in Java the access could be made only less strict in subclasses.)

Code format bug

class A{
public:
  A():_i(1975){}
  int _i;
};

class B : public A
{
public:
  B():_i(333){}
  int i()const{ return _i;}
private:
  int _i; // (1)depricated? no warning in VS2008?
};

class C : public A
{
public:
  C(){} //_i initialized by A
  int i()const{ return _i+1;}
private:
  using A::_i; //(2) should be the right way
};

int main()
{
  B b;
  int i= b.i(); //value of B::_i (333)
  int a_i = static_cast<A*>(&b)->_i; //value of A::_i (1975)

  C c;
  int ca_i = c.i(); //value of A::_i via getter (1975+1)
  //however, A::_i is still accessible  
  a_i = static_cast<A*>(&c)->_i; //value of A::_i (1975)

  return 0;
}

ad (1): I don't see any reason why this should be deprecated. I think it's perfectly legal C++. (The class B adds a second copy of _i which shadows the _i in A , but you can still access the latter by bA::_i .)

ad (2): That does not seem useful at all to me, since you can still access _i in c by using cA::_i , so it isn't hidden at all.

However ugly this code is for me... ( just aesthetic personnal feeling ok).

It is not a hidden member . It is an added member . There is two i in this code. A::_i and B::_i .

After that one can play. But I really dislike when code is misleading in such a way.

出于娱乐目的,有关C ++隐藏功能的GotW讨论:-)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM