开发者

protected data members

why "data members" should be declared "protected"?what c开发者_运维知识库an be the possible benifits?


Protected members are accessible by subclasses, which is not the case if you declare them private.

You declare things to be private or protected to hide them, so that only relevant things which are supposed to be used by the external world are exposed.

If you want to know why whould you want to hide members from the external world, you should get a book about object oriented probramming, because those are basic concepts.


protected simply means that subclasses are able to see that member, but the member is not part of the public API to the object.

Re the question; it depends what you mean by "data members". If you mean fields, then IMO they shouldn't be. It is fairly common to make some state (properties) protected, if subclasses would need that info (in particular methods), but it isn't necessary for the outside world.

A better example, however, is protected virtual, where the inheritor is able to change the implementation of an otherwise private (to the outside world) member. The classic example being:

protected virtual OnSomeMemberChanging(...) {}
protected virtual OnSomeMemberChanged(...) {}

where the inheritor can now react (or even block) changes to key values by using override to change the implementation (commonly but not always calling base.Whatever() at some point to invoke the original implementation as well).


From MSDN

The type or member can be accessed only by code in the same class or struct, or in a class that is derived from that class.

Possible benefits: You restrict the access to the class and its immediate childrens

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜