"Rolf Magnus" <ra******@t-online.de> wrote in message
news:ce*************@news.t-online.com...
Sandeep wrote:
Hi,
In the following code, I wonder how a private member of the class is
being accessed. The code compiles well in Visual Studio 6.0.
I'm not quite sure I understand your problem. Do you think the compiler
shouldn't accept it? The code is fine. The private member x of class
Sample are only accessed from a member function of Sample. If that
weren't allowed, how could the private member variable used at all?
class Sample
{
private:
int x;
public:
void set(Sample& obj) {
x = x + obj.x; //=> private member accessed
}
};
int main(){
Sample obj1;
Sample obj2;
obj1.set(obj2);
return(0);
}
I think the question was about why the "obj.x" part is legal, not the use of
x directly. The object obj is a different object, not the one pointed to by
this->. It's of the same type, but it's not *this* object! So, a natural
question arises about the privacy of obj's members.
If obj were of some other type, then set() would obviously not have access
to its private members (excluding the possibility of friendship, of course).
But it's not readily apparent whether a member function should have access
to private members of *other* instances of the same class.
And I believe the answer is, yes, it does have such access.
Why C++ was designed that way, I don't know. I (at one time) would have
assumed privacy applied in this case also, but if I understand it correctly,
the issue of privacy is applied completely separately from any information
about the actual instance of the class, and only applies to the class type
itself. Thus, *any* instance of an object can access any other instance's
private members, providing they're of the same class.
A quote I read somewhere put it well: "A private member can only be accessed
by member functions of the class (and its friends)." Note that it says
"class", not "object" or "instance". Thus, acces is granted to all
instances of the class, not just the instance in question.
Likewise, protected member status is not related to the actual instance, but
to the class hierarchy itself.
(Is all this talk of accessing one's private members turning anyone else on,
or am I just the sick pervert I think I am? :-))
-Howard