-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
  • 248
  • 1
  • 3
  • 10
  • 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
  • 299,747
  • 42
  • 398
  • 622
  • so I could also write the overloading of the `<<` operator in the class and would thus avoid the use of `friend`? – Hilberto1 Mar 20 '21 at 23:29
  • 1
    @Descrates — yes, but … you can’t write it as a member function because its first argument is an `ostream&`, not a `Complex`. – Pete Becker Mar 20 '21 at 23:31
  • 1
    @Descrates no you can't, because the syntax of `<<` requires it to be a free standing function and not a member. But you could certainly define a public function that `<<` is able to call. – Mark Ransom Mar 20 '21 at 23:31
  • 2
    A [good book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) is the best way to learn C++. – sweenish Mar 20 '21 at 23:37