I just want to make sure I got the idea of public and private right.
Regarding the private access specifier, does it mean:
- Only accessed inside the class
- Cannot be accessed from the object of the class unless there are public class methods that can be used to access them (Can other objects use those public functions?)
- No other object can access them
And for public:
- Accessed from the object of the class
- Accessed from any other object
Is that right?
I think there is an issue of vocabulary to begin with.
In C++ (and most languages) a
class
is atype
. You can think about it as a blueprint to actually build something.An
object
is produced by actually instantiating a class, that is, building what the blueprint described. It is more or a less a bundle of attributes. You can have several objects of the same class as you can have several houses from the same blueprint: note that their physical location is different for obvious reasons :)Now, on to the accessibility. There are 3 typical levels of accessibility:
public
,protected
andprivate
.public
, as expected, means that everyone is given access to either attributes or methodsprotected
is somewhat less trivial. It means that only the object, or its children, may access the attributes (bad idea*) or methods. (Plus, in C++,friend
s)private
means that only the objects of that class (and not their children) may access the attributes or methods (Plus, in C++,friend
s)Note: whatever the level of accessibility, an object has unrestricted access to all the attributes and methods of any object of the same class.
(*) Even though it pops up now and there, it is generally a bad idea to use
protected
attributes. The point of encapsulation is to hide the details, not only for the sake of it, but because by precisely controlling who can access the data, we can ensure that the class maintains its invariants (simple example, an array where you would store the size separately, you need to ensure that the "size" really represents the number of items in the array, at all times). Note: this restriction does not apply when you can seal a hierarchy, like in C# for example.