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?
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.
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.
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. }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With