Understanding Friend Functions in C++

When dealing with private data in a class, it's usually not directly accessible outside that class. However, there's a solution - the friend function.

What is a Friend Function?

A friend function is a special function that allows access to the private data of a class. It's important to note a few key characteristics:

  • Not a Member Function: Unlike regular member functions, a friend function is not part of the class.

  • No Need for an Object: You can invoke a friend function without creating an object of the class.

  • Using an Object's Data: The argument passed to the friend function is treated as its object, giving access to the private data.

Syntax for Friend Function

friend return_type function_name(class_name object);

Example

Let's see an example to better understand friend functions:

#include <iostream>
using namespace std;

class FriendExample {
private:
    int a, b;

public:
    void input() {
        cout << "Enter the value of a and b\n";
        cin >> a >> b;
    }

    // Declaration of the friend function
    friend int compute(FriendExample obj);
};

// Definition of the friend function
int compute(FriendExample obj) {
    int result = obj.a + obj.b;
    return result;
}

int main() {
    FriendExample obj;
    obj.input();
    cout << "The result is: " << compute(obj) << "\n";
    return 0;
}

Output:

Enter the value of a and b
5
6
The result is: 11

In this example, the friend function compute can access the private members of the FriendExample class, showcasing the utility of friend functions in C++.

Next Post Previous Post
No Comment
Add Comment
comment url