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.
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.
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.
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.
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.
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.
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