Member variables are the implementation of the class, not the interface. You may want to change the implementation, so other classes shouldn't be permitted to refer to that implementation directly.
Consider a class with the following methods - C++ syntax, but that isn't important...
class example
{
public:
virtual void Set_Mode (int p_mode);
virtual int Mode () const;
};
It seems pretty obvious that there's going to be a member variable called mode
or m_mode
or similar that directly stores that mode value, doing pretty much what a "property" would do in some languages - but that's not necessarily true. There's a lot of different ways this could be handled. For example, the Set_Mode method might...
- Identify the mode using a switch statement.
- Instantiate a subclass of some internals class, depending on that mode value.
- Store a pointer to that instance as a member variable.
Having done that, many other methods of the example class might then call appropriate methods of that internals class through the pointer, getting mode-specific behaviour without needing to check what the current mode is.
The point here is less that there's more than one possible way to implement this kind of thing, and much more that at some time you may change your mind. Maybe you started with a simple variable, but all the switch statements to identify the mode in every method are getting a pain. Or maybe you started out with the instance-pointer thing, but that turned out to be too heavyweight for your situation.
It turns out that things like this can happen for any member data. You may need to change the units that a value is stored in from miles to kilometers, or you may find that your uniquely-identify-the-case enumerate can no longer uniquely identify all the cases without considering some extra information, or whatever.
This can happen for methods too - some methods are purely for internal use, depend on the implementation, and should be private. But many methods are part of the interface, and won't need to be renamed or whatever just because the internal implementation of the class has been replaced.
Anyway, if your implementation is exposed, other code will inevitably start to depend on it, and you'll be locked into keeping that implementation. If your implementation is hidden from other code, that situation cannot happen.
Blocking access to implementation details is called "data hiding".