Search code examples
c++c++11friend

Operator overloaded functions as friend?


I have a class that represents a special number.

class SecretInteger
{
private:
    unsigned int *data;
    size_t length;

public: 
    SecretInteger operator+(const SecretInteger other) const;
}

I can't allow any other part of my code have access to the data variable. However, my operator+ function MUST be able to see it. Usually in this case I know that using the friend keyword is the only way to do it. However when I write:

friend SecretInteger operator+(const SecretInteger other);

It claims that the operator+ cannot be declared as friend, even though I've previously wrote friend std::ostream& operator<<(std::ostream& stream, const SecretInteger val); and it works fine.

What options do I have available to me? If I have a public method like

const *unsigned int getData() const; I think even then it doesn't actually make the variable returned const right? I'd really prefer not to have a getData() method and instead just declare the functions that have access as friend.


Solution

  • You don't declare a member function as a friend, friend is to give non-member functions access to internals, and a one operand overload of operator+ is a member function.

    In any event, if you implement the binary operators properly, you shouldn't need to give out friendship at all. Implement += as a member function (no need for friend, a class is always "friends" with itself), then implement a non-member + operator in terms of +=, which uses +='s access to the internals to avoid the whole issue of friendship.

    The basic rules for overloading can be found here and should help a lot.