Should you ever use protected member variables?

后端 未结 10 1730
星月不相逢
星月不相逢 2020-12-02 07:53

Should you ever use protected member variables? What are the the advantages and what issues can this cause?

10条回答
  •  有刺的猬
    2020-12-02 08:12

    Generally, if something is not deliberately conceived as public, I make it private.

    If a situation arises where I need access to that private variable or method from a derived class, I change it from private to protected.

    This hardly ever happens - I'm really not a fan at all of inheritance, as it isn't a particularly good way to model most situations. At any rate, carry on, no worries.

    I'd say this is fine (and probably the best way to go about it) for the majority of developers.

    The simple fact of the matter is, if some other developer comes along a year later and decides they need access to your private member variable, they are simply going to edit the code, change it to protected, and carry on with their business.

    The only real exceptions to this are if you're in the business of shipping binary dll's in black-box form to third parties. This consists basically of Microsoft, those 'Custom DataGrid Control' vendors, and maybe a few other large apps that ship with extensibility libraries. Unless you're in that category, it's not worth expending the time/effort to worry about this kind of thing.

提交回复
热议问题