Group: comp.lang.c++
From: red floyd
Date: Friday, February 15, 2008 11:38 AM
Subject: Re: Operator overloading and access to private members

obaqueiro wrote:
> Hello, reading the Thinking in C++ book, i came into this code
> snippter:
>
>
> ----------
> #include <...>...
> // code ommited
>
> class Integer {
> int i;
>
> public:
> Integer (int ii) {i = ii}
>
> const Integer operator+ (const Integer & rv) const {
> return Integer (i+rv.i); //
> ------ Isn't rv.i not visible ?? XXX
> }
>
> const Integer operator= (const Integer & rv){...
> //code ommited}
> };
>
> int main (){
> Integer I(1), J(2), K(3);
> K = I+J;
>
> // This does not compile... of course
> // cout << K.i;
> }
>
>
> -----------
>
> This indeed compiles (in GCC 4). What I can't fully understand why, in
> the line market with the XXX, the function access rv.i where i is a
> private member of the class Integer. Isn't rv.i supposed to be
> inaccessible ? if I try to access K.i in main (the commented code) the
> compiler does throw a "Integer::i is private" error. I would expect
> the same in the other case.
>
> So I think I am missing something, and the specific question would be
> why does this happens? is there any special "visibility" for the
> members of the parameters provided when overloading an operator (i.e.,
> is it possible to see all the private members of the parameters?)
>

rv.i is visible becasue it's a member of Integer. operator+ is also a
member of Integer. What's the problem?

You can't access rv.i from main(), because main() is not a member of
Integer.