Chris Kouts
Chris Kouts

Reputation: 91

Why is "friend" needed in "operator<<()" overload definition?

class Train{
public: 
    char direction;
    int loading_time, crossing_time;        
    ...

    friend std::ostream& operator<<(std::ostream& os, const Train& t){
        os << t.direction << '/' << t.loading_time << '/' << t.crossing_time;
        return os;
    }
};

Why is "friend" needed in this case? All attributes are public. Should I just use a struct instead?

Upvotes: 2

Views: 1398

Answers (1)

Amir Kirsh
Amir Kirsh

Reputation: 13752

The friend is needed in order to make the function global. If you omit it, the function would be considered member function, in which case it should get only one parameter, and the caller should be of type Train (the class type in which we are declared), which doesn't fit our needs.

You can use in your case a global function instead:

class Train{
public: 
    char direction;
    int loading_time, crossing_time;        
    ...

};

std::ostream& operator<<(std::ostream& os, const Train& t){
    os << t.direction << '/' << t.loading_time << '/' << t.crossing_time;
    return os;
}

However, it is very common to use a friend function for this use case (instead of a non-friend global function), as it is declared inside the class, which is an important side bonus that you get.

Upvotes: 7

Related Questions