c++private-membersfriend-functionmember-access

C++ - friend operator cannot access private data members


I am trying to overload an operator for a class:

#include <iostream>
using namespace std;

class Complex{
    float re, im;
public:
    Complex(float x = 0, float y = 0) : re(x), im(y) { }
    friend Complex operator*(float k, Complex c); 
};

Complex operator*(float k, Complex c) {
    Complex prod;
    prod.re = k * re; // Compile Error: 're' was not declared in this scope
    prod.im = k * im; // Compile Error: 'im' was not declared in this scope
    return prod;
}

int main() {
    Complex c1(1,2);
    c1 = 5 * c1;
    return 0;
}

But the friend function doesn't have access to the private data. When I add the object name, the error is resolved:

Complex operator*(float k, Complex c) {
    Complex prod;
    prod.re = k * c.re; // Now it is ok
    prod.im = k * c.im; // Now it is ok
    return prod;
}

But according to the notes that I am reading, the first code should work without error. How can I fix the error without adding the object name (re instead of c.re)?


Solution

  • In the first operator* case, re and im are completely unknown to the compiler as the function operator* in this case is in a global space (scope).

    In the second example of operator* you're giving re and im meaning by using an object of a class Complex c - in this case the definition of a class Complex is known to the compiler (is defined above) and it's members re and im are known too - that is the reason why you're not getting an error message in the second example.