Object Oriented Programming and Encapsulation C++ - c++-cli

Given the below sample class in C++, as you can see one can access all properties/methods for pic1 from the calling module. But only can access to pic2 via those declaration under public. Beside the just mentioned point, as a beginner to object oriented programming, I just wonder which method is preferred by the pro for real life implementation?
using namespace System::Drawing;
using namespace System::Windows::Forms;
using namespace System;
ref class myClass
{
PictureBox^ pic2;
public:
PictureBox^ pic1;
void setPic2() {pic2 = gcnew PictureBox;}
void addPic2ToControl(System::Windows::Forms::Form^ x) {x->Controls->Add(pic2);}
void setPic2Image(String^ filePath) {pic2->Image = dynamic_cast<Image^>(gcnew Bitmap(filePath));}
//more functions for to access pic2...
};

Encapsulation in C++ is usually accomplished by marking fields in your class as private or protected. However, you shouldn't rely on this totally as a way to keep stuff truly private per se-- if this is actually a security issue, for example, it won't help at all (remember friend functions.) It's more intended as a way to "divide-and-conquer" the program complexity and keep the code clean. This is an age-old challenge in computer programming, and encapsulation is just one of many valid techniques programmers have developed over the years.
How should encapsulation be used in your source code? Well a lot of people will insist, for example, that you should never have public variables in your classes, only public methods, and that public variables should be emulated using "getter/setter" functions. I don't necessarily agree with this, but I think it's fair to say that your classes should treat what it does as public information, and how it does it (and its internal state) as private information. This is just common sense anyway, even if you're not doing OOP. Among C programmers, a static (persistant) variable within a function is considered better practice than a variable with global scope if you can get away with it.

What is Encapsulation?
Encapsulation means binding the data and the methods that operate on that data in a single unit.
How do you implement Encapsulation?
By creating a type like structure or a class
Usually the data member variables inside a class are kept under private or protected access specifiers and the access to them is provided through public member functions. This guards honest mistakes of a programmer of accidentally modifying the member data if available publically. It provides a means of accessing and modifying the member data through explicit publically exposed function calls and hence more deliberate and less error prone.
Given the above, I believe, keeping pic2 private and providing access to it through member functions seems to be the appropriate way

One of the pros of restricting access to members through methods is that you now control the management of the variable at a central location (within the class itself). If later you decide to do some processing to pic2 before providing it to the caller you can do that in your access methods without the need to change it at multiple places
Later on if performance is a concern you can consider the option of inlining the methods

Related

Scala and encapsulation?

Since I started to study OOP encapsulation was always something that raised questions to me. Getters and setters in 99% of the cases seemed like a big lie: what does it matter to have setter if it changes the reference of the private field, and getter that returns reference to mutable object? Of course there are many things that make life easier with getters and setters pattern (like Hibernate that creates proxies on entities). In Scala there is some kind of solution: don't lie to yourself, if your field is val you have nothing to fear of and just make it public.
Still this doesn't solve the question of methods, should I ever declare a method private in Scala? Why would I declare a method private in Java? Mostly if it's a helper method and I don't want to pollute my class namespace, and if the method changes our internal state. The second issue doesn't apply (mostly & hopefully) to Scala, and the first one could be simply solved with appropriate traits. So when would I want to declare a method private in Scala? What is the convention for encapsulation in Scala? I would highly appreciate if you help me to order my thoughts on subject.
Getters and setters (or accessor/mutator methods) are used to encapsulate data, which is commonly considered one of the tenets of OOP.
They exist so that the underlying implementation of an object can change without compromising client code, as long as the interface contract remains unchanged.
This is a principle aiming to simplify maintenance and evolution of the codebase.
Even Scala has encapsulation, but it supports the Uniform Access Principle by avoiding explicit use of get/set (a JavaBean convention) by automatically creating accessor/mutator methods that mimics the attribute name (e.g. for a public val name attribute a corresponding def name public accessor is generated and for a var name you also have the def name_= mutator method).
For example if you define
class Encapsulation(hidden: Any, val readable: Any, var settable: Any)
the compiled .class is as follows
C:\devel\scala_code\stackoverflow>javap -cp . Encapsulation
Compiled from "encapsulation.scala"
public class Encapsulation {
public java.lang.Object readable();
public java.lang.Object settable();
public void settable_$eq(java.lang.Object);
public Encapsulation(java.lang.Object, java.lang.Object, java.lang.Object)
}
Scala is simply designed to avoid boilerplate by removing the necessity to define such methods.
Encapsulation (or information hiding) was not invented to support Hibernate or other frameworks. In fact in Hibernate you should be able to annotate the attribute field directly, all the while effectively breaking encapsulation.
As for the usefulness of private methods, it's once again a good design principle that leads to DRY code (if you have more than one method sharing a piece of logic), to better focusing the responsibility of each method, and to enable different composition of the same pieces.
This should be a general guideline for every method you define, and only a part of the encapsulated logic would come out at the public interface layer, leaving you with the rest being implemented as private (or even local) methods.
In scala (as in java) private constructors also allows you to restrict the way an object is instantiated through the use of factory methods.
Encapsulation is not only a matter of getter/setter methods or public/private accessor modifiers. That's a common misconception amongst Java developer who had to spend to much time with Hibernate (or similar JavaBean Specification based libraries).
In object-oriented programming, encapsulation not only refers to information hiding but it also refers to bundling both the data and the methods (operating on that data) together in the same object.
To achieve good encapsulation, there must a clear distinction between the those methods you wish to expose to the public (the so called public interface) and the internal state of an object which must comply with its data invariants.
In Scala the are many ways to achieve object-oriented encapulation. For example, one of my preferred is:
trait AnInterface {
def aMethod(): AType
}
object AnInterface {
def apply() = new AnHiddenImplementation()
private class AnHiddenImplementation {
var aVariable: AType = _
def aMethod(): AType = {
// operate on the internal aVariable
}
}
}
Firstly, define the trait (the public interface) so to make immediately clear what the clients will see. Then write its companion object to provide a factory method which instantiate a default concrete implementation. That implementation can be completely hidden from clients if defined private inside the companion object.
As you can see the Scala code is much more concise of any Java solution

Is there a good reason to use a public property / field?

One of the important parts of object-oriented programming is encapsulation, but public properties / fields tend to break this encapsulation. Under what circumstances does a public property or field actually make sense?
Note: I only use the term 'property' or 'field' because terminology varies between languages. In general, I mean a variable that belongs to an object that can be accessed and set from outside the object.
Yes, there are sometimes good reasons. Information hiding is usually desirable. But there are some occasional exceptions.
For example, public fields are reasonable and useful for:
A C++ pimpl - a struct/class holding the private implementation of another class. Its fields may be declared public syntatically, but are typically accessible only within one source file, by the class holding the pimpl.
Constant fields. For example, Joshua Bloch writes in Effective Java: "Classes are permitted to expose constants via public static final fields."
Structs used for communication between C and C++.
Types which represent only data, whose representation is unlikely to change. For example, javax.vecmath.Point3d, which represents an {x,y,z} coordinate.
Short answer: never.
Actually, if you use an object for simply storing data, but the object itself does no logic, and you never mean to derive from this object, then it is OK to have public fields. Sometimes I do things like this in C++:
struct A {
int a;
float b;
string c;
A():a(0),b(0.0) {}
A(int a_, float b_, string c_):a(a_),b(b_),c(c_) {}
};
But other than having initializing constructors, it is nothing more than a C struct. If your class does anything more than this, than you should never use public (or even protected) fields.
As for properties, it depends on what language you use. For example, in Delphi, the main purpose of properties is to provide public interfaces to fields, and can provide getters/setters to them, while still working syntactically like a variable.
Is there a good reason to use a public
property / field?
No.
Public members are always dangerous. You may not need any control now, but once you expose them, you lose any possibility of having control later. If you have gettes/setters right away you have room for adding control later.
Ps:
Depending on the language you use, properties and fields may mean different things.
C# properties are actually a way to both achieve encapsulation and at the same time not being very verbose.
There is a bad reason: by directly accessing the datum you avoid pushing a method call onto the stack, for what that's worth.
In many languages this is also achievable by inlining the accessor method/s.
If the purpose of the object is to hold data in its fields, then yes. It would also make sense to have methods on the object which are (a) purely functional (in that they do not change the state of the object, or anything else); or (b) which manipulate the state of the object, and the point is that they manipulate the state in a particular way.
The kind of things that you should avoid are (c) methods that do things to other objects based on the state of the object (and certainly if there are assumptions about what is a "valid" state).

Don't static members make classes kind of (global) objects themselves?

Every time I come across an implementation of the singleton pattern or any static classes (i.e. classes with (almost) only static members) I wonder whether this isn't actually a hack and therefore heavy abuse of the principle of classes and instances just to design single objects instead of designing classes and creating a single instance. To me, it looks like static members of classes in general try to add some sort of characteristics to classes which they actually aren't supposed to have and which rather make them object themselves.
But is it really desirable to have single objects implemented like that?
Or do you see things completely differently and don't think that such static classes or singletons have anything in common with actual objects?
Static members are effectively just namespacing for globals, yes. Nothing wrong with that; namespacing is good, and globals are the cleanest way to accomplish some tasks.
Singletons can be somewhat more interesting (load on demand...) but they're a similar construct (yeah, you could think of a static member as an anonymous singleton managed by the compiler).
Like most things, these tools have their place, and only the ideologues worry about whether or not they "fit" with a particular ideology.
Depending on your language, classes are objects. In ruby and java, they're of class Class; in python, I don't remember (subclasses of type?).
In java, you can't avoid putting things on classes. This means you sometimes have to use classes like you would use namespaces and modules. A lot of the static methods on Math are a good example of this. I'd say that having these methods be static makes the best of a bad situation.
I think whether it's "dirty" to have static attributes depends very much on the context. What you really should look for is proper encapsulation: it's good if you can draw a curve through the conceptual space of your code and say "everything on this side doesn't need to know anything about things on that side, except for the interface across the curve.
You can view it from a performance and memory perspective. For example, in the following code:
public class StringUtils
{
public static boolean isEmpty(String value)
{
// some code
}
public static String reverseString(String value)
{
// some code
}
}
Do you really want to instantiate StringUtils objects all over the place just to call a method that doesn't store any member variables? In a simple program, it doesn't matter much. But once your program starts to get to a certain size and you call these methods thousands of times, well let's just the instantiations can add up. And why? To be a purist? It's not worth the cost. Just use the same instance.
Say I have an application which has a single configuration file. How would I create functions to operate on that file without the use of a "singleton" if my language does not support global functions outside of a class (like Java or C#)?
It seems to me the only real way to accomplish that is have a singleton class. Using the singleton pattern you also don't need to pass around a pointer to the object, since you can just use the static method to get it again.
I don't see how this is a violation of any OO principles. To do it a different way, like put the configuration functions in another class that doesn't deal with configuration (like a "utility" class) is more of a violation of OO principles.
Suppose that you have a multi-threaded application which requires a central data repository. The consumers and producers use or put data in the repository, including the external application object which accesses the repository through an interface.
If you made this repository a normal class object, you'd have the problem of initializing it and getting a pointer to every object that needed it. Not the toughest problem, but it can be very confusing with a lot of threads and objects.
On the other hand, if you do this:
public enum Data implements MyInterface{
INSTANCE;
private final Whatevertype secretstuff = new Whatevertype();
...etc...
public void PutThing( Sometype indata){ ... };
public Sometype GetThing( int somecode ){ ...};
...etc...
}
You (a) don't have to instantiate anything and (b) can access from anywhere with
Data.INSTANCE.GetThing(42);
etc. It's just like Highlander... THERE CAN ONLY BE ONE

Should protected attributes always be banned?

I seldom use inheritance, but when I do, I never use protected attributes because I think it breaks the encapsulation of the inherited classes.
Do you use protected attributes ? what do you use them for ?
In this interview on Design by Bill Venners, Joshua Bloch, the author of Effective Java says:
Trusting Subclasses
Bill Venners: Should I trust subclasses more intimately than
non-subclasses? For example, do I make
it easier for a subclass
implementation to break me than I
would for a non-subclass? In
particular, how do you feel about
protected data?
Josh Bloch: To write something that is both subclassable and robust
against a malicious subclass is
actually a pretty tough thing to do,
assuming you give the subclass access
to your internal data structures. If
the subclass does not have access to
anything that an ordinary user
doesn't, then it's harder for the
subclass to do damage. But unless you
make all your methods final, the
subclass can still break your
contracts by just doing the wrong
things in response to method
invocation. That's precisely why the
security critical classes like String
are final. Otherwise someone could
write a subclass that makes Strings
appear mutable, which would be
sufficient to break security. So you
must trust your subclasses. If you
don't trust them, then you can't allow
them, because subclasses can so easily
cause a class to violate its
contracts.
As far as protected data in general,
it's a necessary evil. It should be
kept to a minimum. Most protected data
and protected methods amount to
committing to an implementation
detail. A protected field is an
implementation detail that you are
making visible to subclasses. Even a
protected method is a piece of
internal structure that you are making
visible to subclasses.
The reason you make it visible is that
it's often necessary in order to allow
subclasses to do their job, or to do
it efficiently. But once you've done
it, you're committed to it. It is now
something that you are not allowed to
change, even if you later find a more
efficient implementation that no
longer involves the use of a
particular field or method.
So all other things being equal, you
shouldn't have any protected members
at all. But that said, if you have too
few, then your class may not be usable
as a super class, or at least not as
an efficient super class. Often you
find out after the fact. My philosophy
is to have as few protected members as
possible when you first write the
class. Then try to subclass it. You
may find out that without a particular
protected method, all subclasses will
have to do some bad thing.
As an example, if you look at
AbstractList, you'll find that there
is a protected method to delete a
range of the list in one shot
(removeRange). Why is that in there?
Because the normal idiom to remove a
range, based on the public API, is to
call subList to get a sub-List,
and then call clear on that
sub-List. Without this particular
protected method, however, the only
thing that clear could do is
repeatedly remove individual elements.
Think about it. If you have an array
representation, what will it do? It
will repeatedly collapse the array,
doing order N work N times. So it will
take a quadratic amount of work,
instead of the linear amount of work
that it should. By providing this
protected method, we allow any
implementation that can efficiently
delete an entire range to do so. And
any reasonable List implementation
can delete a range more efficiently
all at once.
That we would need this protected
method is something you would have to
be way smarter than me to know up
front. Basically, I implemented the
thing. Then, as we started to subclass
it, we realized that range delete was
quadratic. We couldn't afford that, so
I put in the protected method. I think
that's the best approach with
protected methods. Put in as few as
possible, and then add more as needed.
Protected methods represent
commitments to designs that you may
want to change. You can always add
protected methods, but you can't take
them out.
Bill Venners: And protected data?
Josh Bloch: The same thing, but even more. Protected data is even more
dangerous in terms of messing up your
data invariants. If you give someone
else access to some internal data,
they have free reign over it.
Short version: it breaks encapsulation but it's a necessary evil that should be kept to a minimum.
C#:
I use protected for abstract or virtual methods that I want base classes to override. I also make a method protected if it may be called by base classes, but I don't want it called outside the class hierarchy.
You may need them for static (or 'global') attribute you want your subclasses or classes from same package (if it is about java) to benefit from.
Those static final attributes representing some kind of 'constant value' have seldom a getter function, so a protected static final attribute might make sense in that case.
Scott Meyers says don't use protected attributes in Effective C++ (3rd ed.):
Item 22: Declare data members private.
The reason is the same you give: it breaks encapsulations. The consequence is that otherwise local changes to the layout of the class might break dependent types and result in changes in many other places.
I don't use protected attributes in Java because they are only package protected there. But in C++, I'll use them in abstract classes, allowing the inheriting class to inherit them directly.
There are never any good reasons to have protected attributes. A base class must be able to depend on state, which means restricting access to data through accessor methods. You can't give anyone access to your private data, even children.
I recently worked on a project were the "protected" member was a very good idea. The class hiearchy was something like:
[+] Base
|
+--[+] BaseMap
| |
| +--[+] Map
| |
| +--[+] HashMap
|
+--[+] // something else ?
The Base implemented a std::list but nothing else. The direct access to the list was forbidden to the user, but as the Base class was incomplete, it relied anyway on derived classes to implement the indirection to the list.
The indirection could come from at least two flavors: std::map and stdext::hash_map. Both maps will behave the same way but for the fact the hash_map needs the Key to be hashable (in VC2003, castable to size_t).
So BaseMap implemented a TMap as a templated type that was a map-like container.
Map and HashMap were two derived classes of BaseMap, one specializing BaseMap on std::map, and the other on stdext::hash_map.
So:
Base was not usable as such (no public accessors !) and only provided common features and code
BaseMap needed easy read/write to a std::list
Map and HashMap needed easy read/write access to the TMap defined in BaseMap.
For me, the only solution was to use protected for the std::list and the TMap member variables. There was no way I would put those "private" because I would anyway expose all or almost all of their features through read/write accessors anyway.
In the end, I guess that if you en up dividing your class into multiple objects, each derivation adding needed features to its mother class, and only the most derived class being really usable, then protected is the way to go. The fact the "protected member" was a class, and so, was almost impossible to "break", helped.
But otherwise, protected should be avoided as much as possible (i.e.: Use private by default, and public when you must expose the method).
The protected keyword is a conceptual error and language design botch, and several modern languages, such as Nim and Ceylon (see http://ceylon-lang.org/documentation/faq/language-design/#no_protected_modifier), that have been carefully designed rather than just copying common mistakes, don't have such a keyword.
It's not protected members that breaks encapsulation, it's exposing members that shouldn't be exposed that breaks encapsulation ... it doesn't matter whether they are protected or public. The problem with protected is that it is wrongheaded and misleading ... declaring members protected (rather than private) doesn't protect them, it does the opposite, exactly as public does. A protected member, being accessible outside the class, is exposed to the world and so its semantics must be maintained forever, just as is the case for public. The whole idea of "protected" is nonsense ... encapsulation is not security, and the keyword just furthers the confusion between the two. You can help a little by avoiding all uses of protected in your own classes -- if something is an internal part of the implementation, isn't part of the class's semantics, and may change in the future, then make it private or internal to your package, module, assembly, etc. If it is an unchangeable part of the class semantics, then make it public, and then you won't annoy users of your class who can see that there's a useful member in the documentation but can't use it, unless they are creating their own instances and can get at it by subclassing.
In general, no you really don't want to use protected data members. This is doubly true if your writing an API. Once someone inherits from your class you can never really do maintenance and not somehow break them in a weird and sometimes wild way.
I use them. In short, it's a good way, if you want to have some attributes shared. Granted, you could write set/get functions for them, but if there is no validation, then what's the point? It's also faster.
Consider this: you have a class which is your base class. It has quite a few attributes you wan't to use in the child objects. You could write a get/set function for each, or you can just set them.
My typical example is a file/stream handler. You want to access the handler (i.e. file descriptor), but you want to hide it from other classes. It's way easier than writing a set/get function for it.
I think protected attributes are a bad idea. I use CheckStyle to enforce that rule with my Java development teams.
In general, yes. A protected method is usually better.
In use, there is a level of simplicity given by using a protected final variable for an object that is shared by all the children of a class. I'd always advise against using it with primitives or collections since the contracts are impossible to define for those types.
Lately I've come to separate stuff you do with primitives and raw collections from stuff you do with well-formed classes. Primitives and collections should ALWAYS be private.
Also, I've started occasionally exposing public member variables when they are declaired final and are well-formed classes that are not too flexible (again, not primitives or collections).
This isn't some stupid shortcut, I thought it out pretty seriously and decided there is absolutely no difference between a public final variable exposing an object and a getter.
It depends on what you want. If you want a fast class then data should be protected and use protected and public methods.
Because I think you should assume that your users who derive from your class know your class quite well or at least they have read your manual at the function they going to override.
If your users mess with your class it is not your problem. Every malicious user can add the following lines when overriding one of your virtuals:
(C#)
static Random rnd=new Random();
//...
if (rnd.Next()%1000==0) throw new Exception("My base class sucks! HAHAHAHA! xD");
//...
You can't seal every class to prevent this.
Of course if you want a constraint on some of your fields then use accessor functions or properties or something you want and make that field private because there is no other solution...
But I personally don't like to stick to the oop principles at all costs. Especially making properties with the only purpose to make data members private.
(C#):
private _foo;
public foo
{
get {return _foo;}
set {_foo=value;}
}
This was my personal opinion.
But do what your boss require (if he wants private fields than do that.)
I use protected variables/attributes within base classes that I know I don't plan on changing into methods. That way, subclasses have full access to their inherited variables, and don't have the (artificially created) overhead of going through getters/setters to access them. An example is a class using an underlying I/O stream; there is little reason not to allow subclasses direct access to the underlying stream.
This is fine for member variables that are used in direct simple ways within the base class and all subclasses. But for a variable that has a more complicated use (e.g., accessing it causes side effects in other members within the class), a directly accessible variable is not appropriate. In this case, it can be made private and public/protected getters/setters can be provided instead. An example is an internal buffering mechanism provided by the base class, where accessing the buffers directly from a subclass would compromise the integrity of the algorithms used by the base class to manage them.
It's a design judgment decision, based on how simple the member variable is, and how it is expected to be so in future versions.
Encapsulation is great, but it can be taken too far. I've seen classes whose own private methods accessed its member variables using only getter/setter methods. This is overkill, since if a class can't trust its own private methods with its own private data, who can it trust?

Should you ever use protected member variables?

Should you ever use protected member variables? What are the the advantages and what issues can this cause?
Should you ever use protected member variables?
Depends on how picky you are about hiding state.
If you don't want any leaking of internal state, then declaring all your member variables private is the way to go.
If you don't really care that subclasses can access internal state, then protected is good enough.
If a developer comes along and subclasses your class they may mess it up because they don't understand it fully. With private members, other than the public interface, they can't see the implementation specific details of how things are being done which gives you the flexibility of changing it later.
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.
The general feeling nowadays is that they cause undue coupling between derived classes and their bases.
They have no particular advantage over protected methods/properties (once upon a time they might have a slight performance advantage), and they were also used more in an era when very deep inheritance was in fashion, which it isn't at the moment.
The key issue for me is that once you make a variable protected, you then cannot allow any method in your class to rely on its value being within a range, because a subclass can always place it out of range.
For example, if I have a class that defines width and height of a renderable object, and I make those variables protected, I then can make no assumptions over (for example), aspect ratio.
Critically, I can never make those assumptions at any point from the moment that code's released as a library, since even if I update my setters to maintain aspect ratio, I have no guarantee that the variables are being set via the setters or accessed via the getters in existing code.
Nor can any subclass of my class choose to make that guarantee, as they can't enforce the variables values either, even if that's the entire point of their subclass.
As an example:
I have a rectangle class with width and height being stored as protected variables.
An obvious sub-class (within my context) is a "DisplayedRectangle" class, where the only difference is that I restrict the widths and heights to valid values for a graphical display.
But that's impossible now, since my DisplayedRectangle class cannot truly constrain those values, as any subclass of it could override the values directly, while still being treated as a DisplayedRectangle.
By constraining the variables to be private, I can then enforce the behaviour I want through setters or getters.
In general, I would keep your protected member variables to the rare case where you have total control over the code that uses them as well. If you are creating a public API, I'd say never. Below, we'll refer to the member variable as a "property" of the object.
Here's what your superclass cannot do after making a member variable protected rather than private-with-accessors:
lazily create a value on the fly when the property is being read. If you add a protected getter method, you can lazily create the value and pass it back.
know when the property been modified or deleted. This can introduce bugs when the superclass makes assumptions about the state of that variable. Making a protected setter method for the variable keeps that control.
Set a breakpoint or add debug output when the variable is read or written to.
Rename that member variable without searching through all the code that might use it.
In general, I think it'd be the rare case that I'd recommend making a protected member variable. You are better off spending a few minutes exposing the property through getters/setters than hours later tracking down a bug in some other code that modified the protected variable. Not only that, but you are insured against adding future functionality (such as lazy loading) without breaking dependent code. It's harder to do it later than to do it now.
At the design level it might be appropriate to use a protected property, but for implementation I see no advantage in mapping this to a protected member variable rather than accessor/mutator methods.
Protected member variables have significant disadvantages because they effectively allow client code (the sub-class) access to the internal state of the base class class. This prevents the base class from effectively maintaining its invariants.
For the same reason, protected member variables also make writing safe multi-threaded code significantly more difficult unless guaranteed constant or confined to a single thread.
Accessor/mutator methods offer considerably more API stability and implementation flexibility under maintenance.
Also, if you're an OO purist, objects collaborate/communicate by sending messages, not reading/setting state.
In return they offer very few advantages. I wouldn't necessarily remove them from somebody else's code, but I don't use them myself.
Just for the record, under Item 24 of "Exceptional C++", in one of the footnotes, Sutter goes
"you would never write a class that has a public or protected member variable. right? (Regardless of the poor example set by some libraries.)"
Most of the time, it is dangerous to use protected because you break somewhat the encapsulation of your class, which could well be broken down by a poorly designed derived class.
But I have one good example: Let's say you can some kind of generic container. It has an internal implementation, and internal accessors. But you need to offer at least 3 public access to its data: map, hash_map, vector-like. Then you have something like:
template <typename T, typename TContainer>
class Base
{
// etc.
protected
TContainer container ;
}
template <typename Key, typename T>
class DerivedMap : public Base<T, std::map<Key, T> > { /* etc. */ }
template <typename Key, typename T>
class DerivedHashMap : public Base<T, std::hash_map<Key, T> > { /* etc. */ }
template <typename T>
class DerivedVector : public Base<T, std::vector<T> > { /* etc. */ }
I used this kind of code less than a month ago (so the code is from memory). After some thinking, I believe that while the generic Base container should be an abstract class, even if it can live quite well, because using directly Base would be such a pain it should be forbidden.
Summary Thus, you have protected data used by the derived class. Still, we must take int o account the fact the Base class should be abstract.
In short, yes.
Protected member variables allow access to the variable from any sub-classes as well as any classes in the same package. This can be highly useful, especially for read-only data. I don't believe that they are ever necessary however, because any use of a protected member variable can be replicated using a private member variable and a couple of getters and setters.
For detailed info on .Net access modifiers go here
There are no real advantages or disadvantages to protected member variables, it's a question of what you need in your specific situation. In general it is accepted practice to declare member variables as private and enable outside access through properties. Also, some tools (e.g. some O/R mappers) expect object data to be represented by properties and do not recognize public or protected member variables. But if you know that you want your subclasses (and ONLY your subclasses) to access a certain variable there is no reason not to declare it as protected.