I instantiate two objects of one class, and one object accesses and changes private fields of the other object. I believe this violates the private access control. It breaks encapsulation in OOP. However, I find that both C++ and Java seem to allow this "violation". Please enlighten me why this "violation" is allowed!
However, I don't think it makes sense to allow this "violation", because it breaks encapsulation in OOP. The fact that we both are human beings does NOT imply that I can access and modify your private stuff. It's no longer your "private stuff" if I can.
Please enlighten me! Is the "violation" a bug of C++ & Java? If I'm wrong, please let me know!
You should not need an object in order to use that function. The reason for the semi-colon at the end of a class or struct is because an object can be defined after it, it is meaningless and confusing to have it for a function.
struct { float x, y; } myStruct;
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Person
{
public:
staticvoid changeAge(Person & p, int k) // change peer object's private fields
{
p.age = k;
} // semi-colon not needed
};
// use
Person::changeAge(p, k);
If you implement a function in Person it has access to any private variable in Person class. It doesn't matter if it's another Person or not it is still of type Person. Wouldn't make sense if you couldn't do this, you are creating the class, you know what everything does (or you should) so nothing needs to be hidden from you.
The fact that we both are human beings does NOT imply that I can access and modify your private stuff. It's no longer your "private stuff" if I can.
That's not the way to think of it.
Think of the class Person as a surgeon, although he doesn't know you personally he knows what's inside you so it doesn't matter from one person to the next you are still the same inside. So he can do the same surgical procedure on you that he can do on someone else.
If you implement a function in Person it has access to any private variable in Person class. It doesn't matter if it's another Person or not it is still of type Person. Wouldn't make sense if you couldn't do this, you are creating the class, you know what everything does (or you should) so nothing needs to be hidden from you.
[quote]
The fact that we both are human beings does NOT imply that I can access and modify your private stuff. It's no longer your "private stuff" if I can.
That's not the way to think of it.
Think of the class Person as a surgeon, although he doesn't know you personally he knows what's inside you so it doesn't matter from one person to the next you are still the same inside. So he can do the same surgical procedure on you that he can do on someone else.
[/quote]
Yes, but it's kina weaird that someone lese can change your AGE! I mean, not even you should be able to do that! LOL