Programming Pandit

c/c++/c#/Javav/Python


Latest Update

Wednesday, September 2, 2026

Friend Function and one for a Friend Class.

Friend Function and Friend Class

1. Friend Function

A friend function is a non-member function that can access the private members of a class.

#include <iostream>
using namespace std;

class A {
    int x = 10;

public:
    friend void show(A obj);
};

void show(A obj) {
    cout << "x = " << obj.x;
}

int main() {
    A obj;
    show(obj);
    return 0;
}

Output:

x = 10

2. Friend Class

A friend class can access the private members of another class.

#include <iostream>
using namespace std;

class B;

class A {
    int x = 10;

    friend class B;
};

class B {
public:
    void show(A obj) {
        cout << "x = " << obj.x;
    }
};

int main() {
    A a;
    B b;
    b.show(a);
    return 0;
}

Output:

x = 10

Simple Difference

Friend FunctionFriend Class
Gives access to one functionGives access to all member functions of a class
Declared using friend inside a classDeclared using friend class
Example: friend void show(A);Example: friend class B;

No comments:

Post a Comment