logo of SA Coder
        Menu
sign in

      References



Friend Classes



Friend classes are an interesting and powerful feature of C++ that allow one class to have access to the private members of another class. This feature can be used to allow certain special case situations to be handled. In this post, we will explore the concept of friend classes in C++ and how they work.



In C++, access control is enforced using public, private, and protected keywords. By default, all members of a class are private, which means they cannot be accessed outside the class. However, if we mark a class as a friend of another class, all of its member functions can access the private members of the other class.



It is important to note that when one class is a friend of another, it only has access to the names defined within the other class. It does not inherit the other class. Specifically, the members of the first class do not become members of the friend class.



Here is an example that demonstrates the use of friend classes in C++


copy

class A {
private:
    int x;

public:
    A(int a) : x(a) {}
    friend class B;
};

class B {
public:
    void display(A obj) {
        // Access the private member of class A
        std::cout << "x = " << obj.x << std::endl;
    }
};

int main() {
    A objA(10);
    B objB;
    objB.display(objA);
    return 0;
}



In this example, we have two classes A and B. Class A has a private member x, and it marks class B as a friend using the friend keyword. Class B has a member function display that takes an object of class A as an argument and accesses its private member x.



When we create an object of class A and an object of class B in the main function, we can call the display function of class B and pass the object of class A as an argument. The display function then accesses the private member x of class A and prints its value to the console.



Friend classes are seldom used, but they can be handy in certain situations where access to private members of another class is necessary. However, it is important to use friend classes with caution as they can break encapsulation and make code harder to maintain.



Please login first to comment.