Search code examples
c++friend-function

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?


Solution

  • 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