Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Violation of encapsulation? [duplicate]

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.

like image 621
sachuraju Avatar asked Oct 11 '12 00:10

sachuraju


People also ask

What violates the principle of encapsulation?

Explanation: Global variables almost always violates the principles of encapsulation. Encapsulation says the data should be accessed only by required set of elements. But global variable is accessible everywhere, also it is most prone to changes. It doesn't hide the internal working of program.

What is encapsulation error?

In general the encapsulation failed error message indicates that the router has a layer 3 packet to forward and is lacking some element of the layer 2 header that it needs to be able to forward the packet toward the next hop.

What are the disadvantages of encapsulation?

Disadvantages of EncapsulationCode Size:The length of the code increases drastically in the case of encapsulation as we need to provide all the methods with the specifiers. More Instructions: As the size of the code increases, therefore, you need to provide additional instructions for every method.


2 Answers

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.

like image 170
SLaks Avatar answered Oct 16 '22 08:10

SLaks


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.

like image 34
bobestm Avatar answered Oct 16 '22 08:10

bobestm