class access clarification needed

Hello all,

i have a operator+ overloaded following way:

1
2
3
4
5
6
complex complex::operator+ (complex rhs) {
    complex tmp;
    tmp.real = real + rhs.real;
    tmp.imag = imag + rhs.imag;
    return tmp;
}

real and imag are private veriables
I also have operator= defined;

when i do
z = x + y; (all are object type complex)

For my understanding:

first x.operator+(y) executed right
my question is how is it possible for rhs to access real and imag? since we can not access private variable directly.

as i think we are currently on object X and its member function operator+. so we can access to X's private variables without any problem.

Since what example is from my prof and it work fine i am sure im wrong, just don't know where?

any help appreciated
Sidenote: I can't see why you haven't passed by reference for rhs and why you haven't included more const keywords, but that is just a pet peeve.

I don't fully understand this question, though from what I can make of it, you are right, the real would access X's private data.
rhs can access real and img because rhs is of class complex.

Does the class complex set values in it's default constructor? I ask because usually in method overloads you don't declare a new class in them. If the object you are in already has data why create a new object?

If you want it to work for the existing object why not:


1
2
3
4
5
complex& complex::operator+ (const complex& rhs) {
    real += rhs.real;
    imag += rhs.imag;
    return *this;
}


if this looks completely foreign, disregard it. It is however, probably what you should be doing. The way you have it is pointless because the number you are returning has nothing to do with the number in the object on the lhs of the + operator because you aren't using it's data.

You CAN access private data directly, just only inside that class or struct's implementation. Or with a friend function, but you will have to look that up yourself if you want.
Last edited on
Topic archived. No new replies allowed.