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

[{'answer_id': 37021, 'author': 'Allain Lalonde', 'author_id': 2443, 'author_profile': 'https://Stackoverflow.com/users/2443', 'pm_score': 7, 'selected': True, 'text': "<blockquote>\n  <p>Should you ever use protected member variables? </p>\n</blockquote>\n\n<p>Depends on how picky you are about hiding state. </p>\n\n<ul>\n<li>If you don't want any leaking of internal state, then declaring all your member variables private is the way to go. </li>\n<li>If you don't really care that subclasses can access internal state, then protected is good enough.</li>\n</ul>\n\n<p>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.</p>\n"}, {'answer_id': 37024, 'author': 'Manu', 'author_id': 2133, 'author_profile': 'https://Stackoverflow.com/users/2133', 'pm_score': 2, 'selected': False, 'text': '<p>For detailed info on .Net access modifiers <a href="https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1027680.html" rel="nofollow noreferrer">go here</a></p>\n\n<p>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.</p>\n'}, {'answer_id': 37025, 'author': 'Will Dean', 'author_id': 987, 'author_profile': 'https://Stackoverflow.com/users/987', 'pm_score': 5, 'selected': False, 'text': "<p>The general feeling nowadays is that they cause undue coupling between derived classes and their bases.</p>\n\n<p>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.</p>\n"}, {'answer_id': 37384, 'author': 'Jay Stramel', 'author_id': 3547, 'author_profile': 'https://Stackoverflow.com/users/3547', 'pm_score': 2, 'selected': False, 'text': "<p>In short, yes.</p>\n\n<p>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.</p>\n"}, {'answer_id': 37407, 'author': 'Orion Edwards', 'author_id': 234, 'author_profile': 'https://Stackoverflow.com/users/234', 'pm_score': 5, 'selected': False, 'text': "<p>Generally, if something is not deliberately conceived as public, I make it private.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>I'd say this is fine (and probably the best way to go about it) for the majority of developers.  </p>\n\n<p><strong>The simple fact of the matter is</strong>, 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.</p>\n\n<p>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.</p>\n"}, {'answer_id': 194655, 'author': 'paercebal', 'author_id': 14089, 'author_profile': 'https://Stackoverflow.com/users/14089', 'pm_score': 2, 'selected': False, 'text': "<p>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.</p>\n\n<p>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:</p>\n\n<pre><code>template &lt;typename T, typename TContainer&gt;\nclass Base\n{\n   // etc.\n   protected\n   TContainer container ;\n}\n\ntemplate &lt;typename Key, typename T&gt;\nclass DerivedMap     : public Base&lt;T, std::map&lt;Key, T&gt; &gt;      { /* etc. */ }\n\ntemplate &lt;typename Key, typename T&gt;\nclass DerivedHashMap : public Base&lt;T, std::hash_map&lt;Key, T&gt; &gt; { /* etc. */ }\n\ntemplate &lt;typename T&gt;\nclass DerivedVector  : public Base&lt;T, std::vector&lt;T&gt; &gt;        { /* etc. */ }\n</code></pre>\n\n<p>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.</p>\n\n<p><strong>Summary</strong> 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.</p>\n"}, {'answer_id': 357451, 'author': 'Michael Bishop', 'author_id': 45114, 'author_profile': 'https://Stackoverflow.com/users/45114', 'pm_score': 3, 'selected': False, 'text': '<p>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.</p>\n\n<p>Here\'s what your superclass <em>cannot</em> do after making a member variable protected rather than private-with-accessors:</p>\n\n<ol>\n<li><p>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.</p></li>\n<li><p>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.</p></li>\n<li><p>Set a breakpoint or add debug output when the variable is read or written to.</p></li>\n<li><p>Rename that member variable without searching through all the code that might use it.</p></li>\n</ol>\n\n<p>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.</p>\n'}, {'answer_id': 2233395, 'author': 'richj', 'author_id': 38031, 'author_profile': 'https://Stackoverflow.com/users/38031', 'pm_score': 3, 'selected': False, 'text': "<p>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.</p>\n\n<p>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.</p>\n\n<p>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.</p>\n\n<p>Accessor/mutator methods offer considerably more API stability and implementation flexibility under maintenance.</p>\n\n<p>Also, if you're an OO purist, objects collaborate/communicate by sending messages, not reading/setting state.</p>\n\n<p>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.</p>\n"}, {'answer_id': 16012209, 'author': 'hAcKnRoCk', 'author_id': 579692, 'author_profile': 'https://Stackoverflow.com/users/579692', 'pm_score': 3, 'selected': False, 'text': '<p>Just for the record, under Item 24 of "Exceptional C++", in one of the footnotes, Sutter goes\n"you would never write a class that has a public or protected member variable. right? (Regardless of the poor example set by some libraries.)"</p>\n'}, {'answer_id': 16570025, 'author': 'deworde', 'author_id': 14250, 'author_profile': 'https://Stackoverflow.com/users/14250', 'pm_score': 3, 'selected': False, 'text': '<p>The key issue for me is that once you make a variable protected, you then cannot allow any method in your class to <em>rely</em> on its value being within a range, because a subclass can always place it out of range.</p>\n\n<p>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.</p>\n\n<p>Critically, I can <em>never</em> 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.</p>\n\n<p>Nor can any subclass of my class choose to make that guarantee, as they can\'t enforce the variables values either, <strong>even if that\'s the entire point of their subclass</strong>.</p>\n\n<p>As an example:</p>\n\n<ul>\n<li>I have a rectangle class with width and height being stored as protected variables.</li>\n<li>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.</li>\n<li><strong>But that\'s impossible now</strong>, since my DisplayedRectangle class <em>cannot</em> truly constrain those values, as any subclass of it could override the values directly, while still being treated as a DisplayedRectangle.</li>\n</ul>\n\n<p>By constraining the variables to be private, I can then enforce the behaviour I want through setters or getters.</p>\n'}]
['https://Stackoverflow.com/questions/37011', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3305/']