Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What operators should be declared as friends?

In some books and often around the internet I see recommendations like "operator== should be declared as friend".

How should I understand when an operator must be declared as friend and when it should be declared as member? What are the operators that will most often need to be declared as friends besides == and <<?

like image 582
Rafael S. Calsaverini Avatar asked Jun 06 '11 17:06

Rafael S. Calsaverini


People also ask

What can be declared as friend in a class?

How can we do it? is it possible to declare a class as friend inside a class? Private member can't declared friend as friend is use to make accessible through another class but private has scope in own class only. But a class may be declared as friend.

Which operator is used for friend function?

Friend function declaration The function uses the dot membership operator .

Why operator must be friends?

Since you do not have access to the stream object (its not yours to modify) these can not be member operators they have to be external to the class. Thus they must either be friends of the class or have access to a public method that will do the streaming for you.

Can operator function be a friend?

Operator function must be either non-static (member function) or friend function.


1 Answers

This really depends on whether a class is going to be on the left- or right-hand side of the call to operator== (or other operator). If a class is going to be on the right-hand side of the expression—and does not provide an implicit conversion to a type that can be compared with the left-hand side—you need to implement operator== as a separate function or as a friend of the class. If the operator needs to access private class data, it must be declared as a friend.

For example,

class Message {     std::string content; public:     Message(const std::string& str);     bool operator==(const std::string& rhs) const; }; 

allows you to compare a message to a string

Message message("Test"); std::string msg("Test"); if (message == msg) {     // do stuff... } 

but not the other way around

    if (msg == message) { // this won't compile 

You need to declare a friend operator== inside the class

class Message {     std::string content; public:     Message(const std::string& str);     bool operator==(const std::string& rhs) const;     friend bool operator==(const std::string& lhs, const Message& rhs); }; 

or declare an implicit conversion operator to the appropriate type

class Message {     std::string content; public:     Message(const std::string& str);     bool operator==(const std::string& rhs) const;     operator std::string() const; }; 

or declare a separate function, which doesn't need to be a friend if it doesn't access private class data

bool operator==(const std::string& lhs, const Message& rhs); 
like image 111
Chris Frederick Avatar answered Sep 25 '22 13:09

Chris Frederick