PsychoRhano
PsychoRhano

Reputation: 29

Compiler doesn't recognize friend function

A friend function can't be recognized

#include <iostream>
#include <cmath>

class hello {
    private:
        int a, b;
public: 
    hello(int a, int b) {
        this->a = a;
        this->b = b;
    }
friend int add();
};

int add() {
return a + b;
}

int main() {
hello number(1, 2);
std::cout << number.add();
}

Expected: It should add the 2 membervariables of the class hello (with the friend function!)

Actual result: The friend function "add" is not recognized as a class member

(error message: error: 'class hello' has no member named 'add')

The a and b in add() aren't recognized too. (obviously)

Upvotes: 0

Views: 113

Answers (1)

user11313931
user11313931

Reputation:

That’s not how friend functions work. A friend function is a normal function (not a member function) which means that it is not associated with a particular object instance. The only difference between it and a not-friend function is that friends are allowed to access private members of the class that they are friends with.

If you want to be able to access members of a particular object instance, you should either use a member function instead of a friend function:

class hello {
    int a, b;
public:
    int add() { return a + b; }
}

or take an object instance as a parameter in the friend function:

int add(const hello& instance) {
    return instance.a + instance.b;
}

Upvotes: 6

Related Questions