Home > Net >  Overloading the arithmetic operators using friend functions
Overloading the arithmetic operators using friend functions

Time:11-15

I found an example of how to overload arithmetic operators using friend functions, and the overloaded operator function is defined inside the class with comments stating that:

/* This function is not considered a member of the class, even though the definition is 
    inside the class */

this is the example:

#include <iostream>

class Cents
{
private:
    int m_cents {};

public:
    Cents(int cents) : m_cents{ cents } { }

    // add Cents   Cents using a friend function
        // This function is not considered a member of the class, even though the definition is inside the class
    friend Cents operator (const Cents& c1, const Cents& c2)
    {
        // use the Cents constructor and operator (int, int)
        // we can access m_cents directly because this is a friend function
        return Cents{c1.m_cents   c2.m_cents};
    }

    int getCents() const { return m_cents; }
};

int main()
{
    Cents cents1{ 6 };
    Cents cents2{ 8 };
    Cents centsSum{ cents1   cents2 };
    std::cout << "I have " << centsSum.getCents() << " cents.\n";

    return 0;
}

Is this function really not a member of that class? and are all friend functions defined inside the class but not a member of that class or It is only for overloaded functions using the friend keyword.

CodePudding user response:

Is this function really not a member of that class?

Yes.

and are all friend functions defined inside the class but not a member of that class

Yes.

To put it simply, you are not your friend. Your friend might have access to all your things (access to class members), and live in your house (defined inside class body), but they are still not you (a member of the class). They are separate from the class and the only coupling is they have access to the class members.

CodePudding user response:

From the C 17 Standard (12.2 Class members)

2 A member-declaration does not declare new members of the class if it is

(2.1) — a friend declaration (14.3),

(2.2) — a static_assert-declaration,

(2.3) — a using-declaration (10.3.3), or

(2.4) — an empty-declaration.

For any other member-declaration, each declared entity that is not an unnamed bit-field (12.2.4) is a member of the class, and each such member-declaration shall either declare at least one member name of the class or declare at least one unnamed bit-field.

and (14.3 Friends)

1 A friend of a class is a function or class that is given permission to use the private and protected member names from the class. A class specifies its friends, if any, by way of friend declarations. Such declarations give special access rights to the friends, but they do not make the nominated friends members of the befriending class.

So friend functions are not members of the class where they are declared as friend functions even if they are also defined in the class.

  • Related