6

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.

Community
  • 1
  • 1
sachuraju
  • 123
  • 8

2 Answers2

7

No.

Encapsulation works at the class level, not at the instance level.

You can access private members of any instance of your class.
You can even access private members defined by your class through a reference to a class derived from your class.

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
2

This is not a violation of encapsulation because you are accessing a member variable in a method both of which belong to the same class. If obj2 was a reference of another class eg yourClass, then it would be a violation as you were accessing a private member of another class.

bobestm
  • 1,334
  • 1
  • 9
  • 8