-1

Consider the following code snippet:

class Complex {
    double real, im;
    public:
    Complex(double real, double im) {
        this->real = real;
        this->im = im;
    } 
    Complex operator + (Complex const& sec) {
        Complex ret(real + sec.real, im + sec.im);
        return ret;
    }
    friend ostream& operator<<(ostream& os, const Complex& com);
};

ostream& operator << (ostream& os, const Complex& com) {
    os << com.real << " " << com.im << "i";
    return os;
}

Why doesn't the operator overloading of + have to be declared as friend as it will also want to access the private variables of the class from outside, similar to when overloading the << operator? At least that's what I thought but apparently this is not the case.

Hilberto1
  • 178
  • 2
  • 9
  • since a lot of ppl think that they know everything here is a good link for you. https://www.learncpp.com/cpp-tutorial/overloading-the-io-operators/ –  Mar 20 '21 at 23:50
  • There was an article explaining why `operator<>>` were implemented this way but I cannot find it, and why they cannot be members of your class. –  Mar 20 '21 at 23:54
  • and pls read this: https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading/4421729#4421729. As I said in an answer LHO (object that you are modifying) has to be of your own class. –  Mar 21 '21 at 00:10
  • 1
    Does this answer your question? [What are the basic rules and idioms for operator overloading?](https://stackoverflow.com/questions/4421706/what-are-the-basic-rules-and-idioms-for-operator-overloading) –  Mar 21 '21 at 00:11

1 Answers1

3

A member function can access all the variables of a class, public or private. You only need friend for functions or classes that aren't part of your class.

Mark Ransom
  • 286,393
  • 40
  • 379
  • 604