Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 548
Chris Kouts Avatar asked Nov 30 '25 03:11

Chris Kouts


1 Answers

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.

like image 190
Amir Kirsh Avatar answered Dec 02 '25 19:12

Amir Kirsh