0

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)

  • 3
    That's not what a friend function is. A friend function is a regular function that is capable of accessing a class's private class members. That's it. Nothing more. Nothing less. You have: "`int add() { return a+b; }`". What is "a"? What is "b"? `add()` is just a function. Just because it is a friend function doesn't make it a class method. – Sam Varshavchik Jul 05 '19 at 16:22
  • Do you know what `friend` function is, and how it's different from member function? Since it seems that you want member function (method) here. Consider learning from a [good C++ book](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) instead of coding randomly. – Algirdas Preidžius Jul 05 '19 at 16:22

1 Answers1

6

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;
}