Possible Duplicate:
Why do objects of the same class have access to each other’s private data?
Something I have never understood with trying to keep encapsulation:
Say I have a class called GameObject
, and a derived class called Human
. GameObject
has a private variable position
. I have multiple instances of Human
, I want each human to be able to call SetPos()
and set it's position as it wants. I do not however want one human to have the power to set up the position of another human. This is my problem.
If I have SetPos
public or protected, each human can alter each others positions, if SetPos()
is private, a human cannot even set its own position ( I need this, might be a weak example but I hope you understand).
Can anyone offer a solution?
Thanks.
if SetPos() is private, a human cannot even set its own position
Actually, it can, if SetPos
is defined on Human
. A private
method can only be called from inside the class, but it does not protect instances of the same class from each other:
class Human {
private:
void set_pos(int i) { std::cout << "moving to " << i << std::endl; }
public:
void set_pos_on_other(Human &other, int i) const { other.set_pos(i); }
};
int main()
{
Human alice, bob;
bob.set_pos_on_other(alice, 10);
}
If SetPos
is defined on GameObject
and it has to be called by a Human
, even if only on itself, then it needs to be protected
or public
.
To solve the problem of objects calling each other's private
methods, you simply need to program carefully and stick to your invariants. C++ offers no special syntax for this. Whenever a Human
method gets passed a reference or pointer to another Human
, it can call that Human
's private
methods all it wants.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With