nowox
nowox

Reputation: 29096

Why is friend keyword required when overloading operator<<?

In the following example all my members are public so I don't understand why I still need to add the friend keyword. Moreover, this method belongs to a Point instance, so I also don't understand why I should refer to my attributes through const Point% p. In the + overload only the foreign instance is received.

#include <iostream>

struct Point {
    int x, y;
    Point(int x, int y): x(x), y(y) {};
    Point operator+(const Point& other) const {
        return Point(x + other.x, x + other.y);
    }

    friend std::ostream& operator<<(std::ostream& os, const Point& p) {
        return os << "(" << p.x << "," << p.y << ")";
    }
};

int main() {
    Point p = Point(4,7) + Point(8,3);
    std::cout << p << std::endl;
}

Similar questions such as this one are not really helpful in this case.

Upvotes: 1

Views: 135

Answers (1)

Pete Becker
Pete Becker

Reputation: 76245

No, you don't have to make the stream inserter here a friend. The problem is that the code defines the inserter inside the class definition. Without any decorations it would be an ordinary member function, and calling it would be a syntactic nightmare. You could make it a static member, but that's counterintuitive. The reason that friend makes it works is a side effect: marking it as a friend pushes its definition outside the class definition. So instead of using friend, just define it outside the class definition.

#include <iostream>

struct Point {
    int x, y;
    Point(int x, int y): x(x), y(y) {};
    Point operator+(const Point& other) const {
        return Point(x + other.x, x + other.y);
    }

};

std::ostream& operator<<(std::ostream& os, const Point& p) {
    return os << "(" << p.x << "," << p.y << ")";
}

int main() {
    Point p = Point(4,7) + Point(8,3);
    std::cout << p << std::endl;
}

Upvotes: 3

Related Questions