- Learn C++ - http://www.learncpp.com -

9.2a — Overloading operators using normal functions

In the previous lesson, we overloaded operator+ as a friend function:

Using a friend function to overload an operator is convenient because it gives you direct access to the internal members of the classes you’re operating on. In the initial Cents example above, our friend function version of operator+ accessed member variable m_cents directly.

However, if you don’t need that access, you can write your overloaded operators as normal functions. Note that the Cents class above contains an access function (getCents()) that allows us to get at m_cents without having to have direct access to private members. Because of this, we can write our overloaded operator+ as a non-friend:

Because the normal and friend functions work almost identically (they just have different levels of access to private members), we generally won’t differentiate them. The one difference is that the friend function declaration inside the class serves as a prototype as well. With the normal function version, you’ll have to provide your own function prototype.

Cents.h:

Cents.cpp:

main.cpp:

In general, a normal function should be preferred over a friend function if it’s possible to do so with the existing member functions available (the less functions touching your classes’s internals, the better). However, don’t add additional access functions just to overload an operator as a normal function instead of a friend function!

Rule: Prefer overloading operators as normal functions instead of friends if it’s possible to do so without adding additional functions.

9.3 -- Overloading the I/O operators [1]
Index [2]
9.2 -- Overloading the arithmetic operators using friend functions [3]