Shubham Urkade
Shubham Urkade

Reputation: 43

What's the use of a friend function in a struct?

I'm overloading the insertion operator (<<) inside a struct using the following syntax:

struct Address{
    string street;
    string cross;
    int suite;

    friend ostream &operator <<(ostream &oss, const Address &other){
        oss<<"street: "<<other.street<<"cross: "<<other.cross<<"suite: "<<other.suite;
        return oss;
    }
};

I see that only if I declare the function as a friend of struct 'Address' does my code compile. As per my understanding a friend function is useful when there's a need to access the private members of a class. But, since in a struct all the members are public, there shouldn't be a need to declare the '<<' operator as a friend.

Could anybody please clarify the need of declaring '<<' operator here as a friend of the struct 'Address'?

Upvotes: 1

Views: 2895

Answers (1)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385224

Indeed, that operator can be defined at namespace scope without friend.

You do not "need" to make it a friend in this case, for exactly the reasons you give, so it's not clear where you've heard that you do!

struct Address
{
   string street;
   string cross;
   int suite;
};

inline ostream& operator<<(ostream& oss, const Address& other)
{
   oss << "street: " << other.street << "cross: " << other.cross << "suite: " << other.suite;
   return oss;
}

(I made it inline on the assumption you're keeping the whole definition in the header, though in reality I'd probably declare it in the header then define it elsewhere.)

However a class defined with struct is still just a class and can still contain private members just fine. If you had one that did, you would once again need a friend.

Some people may choose to always make a friend function for consistency, and so that the definition of operator<< looks like it's "in" the class when you read it. Alternatively there may be some arcane lookup constraints that make this convenient (since a friend function defined in this way can only be found by ADL), though I can't think of any off the top of my head.

Upvotes: 7

Related Questions