Private and Protected Members : C++

2019-01-01 03:08发布

Can someone enlighten me as to the difference between private and protected members in classes?

I understand from best practice conventions that variables and functions which are not called outside the class should be made private - but looking at my MFC project, MFC seems to favor protected.

What's the difference and which should I use?

标签: c++ class mfc
16条回答
人气声优
2楼-- · 2019-01-01 03:19

Sure take a look at the Protected Member Variables question. It is recommended to use private as a default (just like C++ classses do) to reduce coupling. Protected member variables are most always a bad idea, protected member functions can be used for e.g. the Template Method pattern.

查看更多
长期被迫恋爱
3楼-- · 2019-01-01 03:19

A protected nonstatic base class member can be accessed by members and friends of any classes derived from that base class by using one of the following:

  • A pointer to a directly or indirectly derived class
  • A reference to a directly or indirectly derived class
  • An object of a directly or indirectly derived class
查看更多
梦醉为红颜
4楼-- · 2019-01-01 03:20

private = accessible by the mothership (base class) only (ie only my parent can go into my parent's bedroom)

protected = accessible by mothership (base class), and her daughters (ie only my parent can go into my parent's bedroom, but gave son/daughter permission to walk into parent's bedroom)

public = accessible by mothership (base class), daughter, and everyone else (ie only my parent can go into my parent's bedroom, but it's a house party - mi casa su casa)

查看更多
看淡一切
5楼-- · 2019-01-01 03:20

Private member can be accessed only in same class where it has declared where as protected member can be accessed in class where it is declared along with the classes which are inherited by it .

查看更多
深知你不懂我心
6楼-- · 2019-01-01 03:23

Attributes and methods marked as protected are -- unlike private ones -- still visible in subclasses.

Unless you don't want to use or provide the possibility to override the method in possible subclasses, I'd make them private.

查看更多
伤终究还是伤i
7楼-- · 2019-01-01 03:23

Protected members can only be accessed by descendants of the class, and by code in the same module. Private members can only be accessed by the class they're declared in, and by code in the same module.

Of course friend functions throw this out the window, but oh well.

查看更多
登录 后发表回答