Possible Duplicate:
Class Data Encapsulation(private data) in operator overloading
Please look at this example.
class myClass {
int a;
public :
myClass () {
this->a = 0;
}
myClass(int val) {
this->a = val;
}
void add(myClass &obj2) {
cout << "Result = " << this->a + obj2.a;
obj2.a = 0;
}
void show() {
cout << "a = " << this->a;
}
};
int main() {
myClass obj1(10), obj2(20);
obj2.show(); //prints 20.
obj1.add(obj2);
obj2.show(); //prints 0.
return 0;
}
In the add() function, I am able to access the value of a private member of obj2 when I've actually called add() in the context of obj1. Isn't this a violation of encapsulation?
At first I was thinking that the compiler will throw me an error, but it didn't.