Question about Friend functions used in C++

91 Views Asked by At

I am working with a C++ class that includes a friend function for calculations. However, I noticed that even though the friend function is declared within the class, it seems to work without being defined inside the class body. The program runs successfully, and the friend function is able to access the private member data of the class. Why does this work, and is it considered good practice to define the friend function outside the class in this way? I'm confused about the role of friend functions and whether they need to be defined within the class body.

#include <iostream>
using namespace std;
class MyClass {
private:
    int data;

public:
    MyClass(int d) {
        data = d;
    };
    friend void myFriendFunction(MyClass& obj);
};
void myFriendFunction(MyClass& obj) {
    cout << "Friend function accessing private data: " << obj.data << endl;
}

int main() {
    MyClass myObject(42);
    myFriendFunction(myObject);
    return 0;
}

1

There are 1 best solutions below

1
Nikolay Pervushev On

Declaring function as a friend inside of class is enough. Class has to confirm that function that is trying to access it's private members is a friend of this class and therefore has right to do it. That is what's happening in your code.

As far as i know friend function should be defined outside of class body. If you define it inside then why won't make it a method of this class?