Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why should we use a friend function to define the comparison operator?

From http://www.learncpp.com/cpp-tutorial/142-function-template-instances/

class Cents
{
private:
    int m_nCents;
public:
    Cents(int nCents)
        : m_nCents(nCents)
    {
    }

    friend bool operator>(Cents &c1, Cents&c2)  // <--- why friend?
    {
        return (c1.m_nCents > c2.m_nCents) ? true: false;
    }
};

We could have also implemented it like this:

class Cents
{
private:
    int m_nCents;
public:
    Cents(int nCents)
        : m_nCents(nCents)
    {
    }

    bool operator> (Cents& c2)  // <---
    {
        return (this->m_nCents > c2.m_nCents) ? true: false;
    }
};

Is there any downside of using the second implementation?

like image 857
Lazer Avatar asked Feb 28 '12 05:02

Lazer


People also ask

Why is it necessary to declare a function as a friend function?

A friend function is a special function in C++ which in-spite of not being member function of a class has privilege to access private and protected data of a class. A friend function is a non member function or ordinary function of a class, which is declared as a friend using the keyword “friend” inside the class.

Why do we need friend function for operator overloading?

Operator overloading of non-member function or friend function. A non-member function does not have access to the private data of that class. This means that an operator overloading function must be made a friend function if it requires access to the private members of the class.

How do you define a comparison operator in C++?

Comparison Operators == and != The comparison operators are very simple. Define == first, using a function signature like this: bool MyClass::operator==(const MyClass &other) const { ... // Compare the values, and return a bool result. }


1 Answers

Assuming you are using const references as the parameters, the first implementation can be used in conditions like this: bool b = 42 > c; which will provide a compiler error in the second implementation. This will automatically creates a Cent object using the integer 42 (since constructor is not defined as explicit) and then use the friend function for comparison. See point 7 in this FAQ

like image 64
Naveen Avatar answered Oct 01 '22 01:10

Naveen