thisis not special. Access is granted or denied based on the class of the reference/pointer/object, not based on the name of the reference/pointer/object. (See below for the fine print.)
The fact that C++ allows a class’ methods and friends to access the non-
publicparts of all its objects, not just the
thisobject, seems at first to weaken encapsulation. However the opposite is true: this rule preserves encapsulation. Here’s why.
Without this rule, most non-
publicmembers would need a
publicget method, because many classes have at least one method or friend that takes an explicit argument (i.e., an argument not called
this) of its own class.
Huh? (you ask). Let’s kill the mumbo jumbo and work out an example:
Consider assignment operator
Foo::operator=(const Foo& x). This assignment operator will probably change the data members in the left-hand argument,
*this, based on the data members in the right-hand argument,
x. Without the C++ rule being discussed here, the only way for that assignment operator to access the non-
xwould be for class
Footo provide a
publicget method for every non-
publicdatum. That would suck bigtime. (NB: “suck bigtime” is a precise, sophisticated, technical term; and I am writing this on April 1.)
The assignment operator isn’t the only one that would weaken encapsulation were it not for this rule. Here is a partial(!) list of others:
- Copy constructor.
- Comparison operators:
- Binary arithmetic operators:
- Binary bitwise operators:
- Static methods that accepts an instance of the class as a parameter.
- Static methods that creates/manipulates an instance of the class.
Conclusion: encapsulation would be shredded without this beneficial rule: most non-
publicmembers of most classes would end up having a
The Fine Print: There is another rule that is related to the above: methods and friends of a derived class can access the
protectedbase class members of any of its own objects (any objects of its class or any derived class of its class), but not others. Since that is hopelessly opaque, here’s an example: suppose classes
D2inherit directly from class
B, and base class
x. The compiler will let
D1’s members and friends directly access the
xmember of any object it knows to be at least a
D1, such as via a
D1object, etc. However the compiler will give a compile-time error if a
D1member or friend tries to directly access the
xmember of anything it does not know is at least a
D1, such as via a
D2object, etc. By way of (imperfect!!) analogy, you are allowed to pick your own pockets, but you are not allowed to pick your father’s pockets nor your brother’s pockets.