tags:

views:

59

answers:

3

hi, why "data members" should be declared "protected"?what can be the possible benifits?

+3  A: 

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.

Palantir
thanks but is this the only benifit.
user
This is all about protection and project tidyness and maintainability. It has nothing to do with performance or anything. You can make everything public and be happy (but that will be harder to maintain and quite unprofessional).
Palantir
A: 

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

Ramesh Vel
not just immediate; all descendants. Also; you can't inherit from a struct so that is moot.
Marc Gravell
A: 

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).

Marc Gravell