Reputation: 4552
class Foo
{
public:
void someFunk( Foo &bar );
private:
int a;
...
};
void Foo::someFunk( Foo &bar )
{
a = bar.a;
}
I noticed that objects passed as parameters are allowed to access private data members. I can see why for the this pointer, but shouldn't an object passed as a parameter have to call an accessor? I thought this would be wrong but code is compiling for me.
Upvotes: 3
Views: 2508
Reputation: 308530
The definition of private
means it's private to the class, not to the object. Any object of the class can access another class object's members. This is essential for implementing copy constructors, for example.
Upvotes: 3
Reputation: 39429
I don't know what the official rationale is for this, but it seems to me that being able to access private members of another object of your own class does not break encapsulation, nor does it create any additional coupling.
The point of encapsulation is that an object of class A should not know the inner workings of an object of class B, so that the implementation of B can change without affecting A. But any object of class A by definition knows the internals of any other object of class A. In other words, it makes sense to talk about coupling between two different classes, but it does not make sense to talk about coupling between two objects of the same class.
On a more practical level, if you could not access private members of an object of the same class, how would you implement a copy constructor? You would have to have a accessor for each private member, which is only one step away from making it public. Not to mention providing a getter for every private member would make your class unnecessarily large and hard to maintain.
Upvotes: 5
Reputation: 144206
It depends on the language - in C# (and C++ it appears) members are private to the class rather than the instance. In other languages such as Ruby, members are accessible only to the instance.
Upvotes: 1