access private members in inheritance

主宰稳场 提交于 2019-12-02 18:59:19

Quick answer: You don't. Thats what the protected key-word is for, which you want to use if you want to grant access to subclasses but no-one else.

private means that no-one has access to those variables, not even subclasses.

If you cannot change code in A at all, maybe there is a public/protected access method for that variable. Otherwise these variables are not meant to be accessed from subclasses and only hacks can help (which I don't encourage!).

Schehaider Aymen

Private members of a base class can only be accessed by base member functions (not derived classes). So you have no rights not even a chance to do so :)

class Base

  • public: can be accessed by anybody
  • private: can only be accessed by only base member functions (not derived classes)
  • protected: can be accessed by both base member functions and derived classes

Well, if you have access to base class, you can declare class B as friend class. But as others explained it: because you can, it does not mean it's good idea. Use protected members, if you want derived classes to be able to access them.

It is doable as describe in this Guru of the Week - GotW #76 - Uses and Abuses of Access Rights. But it's should be considered a last resort.

You need to define it as protected. Protected members are inherited to child classes but are not accessible from the outside world.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!