Click to See Complete Forum and Search --> : Member function accessing private members of objects of same type passed by reference


darsonsc
January 16th, 2008, 07:57 AM
Hi,
I am having difficulty understanding the concept of a member function of a class-type which takes a parameter by reference of an object of the same class-type, be able to access the private members of the object that was passed in to this member function.
class Foo
{
public:
Foo(int i):val(i) { }
void Access_Object(Foo &another_object)
{
cout << another_object.val << endl;
//how is it that the member function of an object is being allowed to access
//the private member of another_object passed in by reference...just because it is of the same class?
}
private:
int val;
};
int main( )
{
Foo obj1(5);
Foo obj2(10);
obj1.Access_Object(obj2);
//why is obj1's member function being allowed to access
//the private member of obj2?
return 0;
}

JohnW@Wessex
January 16th, 2008, 08:35 AM
It comes down the fact that member access permissions in C++ are 'by class' not 'by object'.

If it wasn't the case I'm not sure you could write a copy constructor or assignment operator.

MyClass(const MyClass &instance_of_myclass)

MyClass & operator = (const MyClass &instance_of_myclass)

darsonsc
January 16th, 2008, 04:06 PM
Thanks, John. That was the same argument I had to convince myself. I guess that I will have to leave it at that until, I read the "C++ Object Model" by Lippman. It's in my list, will get there soon. Thanks again