Introduction to C++ | Friend Function | Friend Class

C++ Friend Function

A friend function in C++ is a function that is not a member of a class but has the ability to access the private and protected members of the class. By using the friend keyword, you can allow specific functions or entire classes to access the private and protected data of a class. A friend function can be a regular function, a method from another class, or even another class itself.

Why Use Friend Functions?

In some cases, it's necessary to give a function access to the internal workings of a class, even though it is not a member of that class. This is where friend functions come in handy. They are typically used when two or more classes need to closely work together, but you don't want to make them directly members of each other.

Syntax of a Friend Function

The syntax of declaring a friend function within a class is as follows:

Syntax of Friend Function


        class ClassName {
            // Other members of the class
            friend returnType functionName(parameters);  // Friend function declaration
        };
                    

Example: Friend Function

In the following example, a function addNumbers is declared as a friend of the class Box, so it can access the private members of Box:

Code Example: Friend Function


        #include <iostream>
        using namespace std;
        
        class Box {
        private:
            int length;
            int breadth;
        
        public:
            // Constructor
            Box(int l, int b) : length(l), breadth(b) {}
        
            // Declare the friend function
            friend int addNumbers(Box);  // Friend function declaration
        };
        
        // Friend function definition
        int addNumbers(Box b) {
            return b.length + b.breadth;
        }
        
        int main() {
            Box box(10, 20);
            
            // Accessing private members using the friend function
            cout << "The sum of length and breadth is: " << addNumbers(box) << endl;
        
            return 0;
        }
                    

Output:

The sum of length and breadth is: 30

Friend Function of Another Class

A friend function can also be a method of another class. Here's an example where the add function is a friend of the class Box and a method of another class Calculator.

Code Example: Friend Function of Another Class


        #include <iostream>
        using namespace std;
        
        class Box {
        private:
            int length;
            int breadth;
        
        public:
            // Constructor
            Box(int l, int b) : length(l), breadth(b) {}
        
            // Declare friend class
            friend class Calculator;  // Friend class declaration
        };
        
        class Calculator {
        public:
            int add(Box b) {
                return b.length + b.breadth;  // Access private members of Box
            }
        };
        
        int main() {
            Box box(5, 15);
            Calculator calc;
        
            // Access private members using the friend class
            cout << "The sum of length and breadth is: " << calc.add(box) << endl;
        
            return 0;
        }
                    

Output:

The sum of length and breadth is: 20

Key Points About Friend Functions

Friend Class in C++

In C++, a friend class is a class that has access to the private and protected members of another class. This is useful when two or more classes need to collaborate and share private data. The friendship is established by declaring the friend class inside the other class using the friend keyword.

Key Features of Friend Classes

Syntax

Friend Class Syntax


        class ClassA {
            private:
                int privateData;
        
            public:
                ClassA() : privateData(0) {}
        
                // Declaring ClassB as a friend
                friend class ClassB;
        };
        
        class ClassB {
            public:
                void accessClassA(ClassA& obj) {
                    obj.privateData = 10; // Accessing private member of ClassA
                    cout << "Private data of ClassA: " << obj.privateData << endl;
                }
        };
                    

Example of Friend Class

In this example, ClassB is declared as a friend of ClassA, allowing it to access private data of ClassA.

Code Example


        #include <iostream>
        using namespace std;
        
        class ClassA {
            private:
                int privateData;
        
            public:
                ClassA() : privateData(0) {}
                
                // Declaring ClassB as a friend
                friend class ClassB;
        };
        
        class ClassB {
            public:
                void accessClassA(ClassA& obj) {
                    // Accessing and modifying private member of ClassA
                    obj.privateData = 42;
                    cout << "Accessing private data of ClassA: " << obj.privateData << endl;
                }
        };
        
        int main() {
            ClassA objA;
            ClassB objB;
        
            // ClassB accessing private member of ClassA
            objB.accessClassA(objA);
        
            return 0;
        }
                    

Output

Accessing private data of ClassA: 42

Use Cases of Friend Classes

Friend classes are commonly used in the following scenarios:

Important Points

Advanced Example

This example demonstrates the use of a friend class in a more complex scenario where multiple classes collaborate.

Code Example: Multiple Friend Classes


        #include <iostream>
        using namespace std;
        
        class ClassA;
        
        class ClassB {
            public:
                void modifyClassA(ClassA& objA); // Forward declaration
        };
        
        class ClassA {
            private:
                int privateData;
        
            public:
                ClassA() : privateData(100) {}
        
                // Declaring ClassB as a friend
                friend class ClassB;
        
                void displayData() {
                    cout << "Private data of ClassA: " << privateData << endl;
                }
        };
        
        void ClassB::modifyClassA(ClassA& objA) {
            objA.privateData += 50; // Access and modify private data
        }
        
        int main() {
            ClassA objA;
            ClassB objB;
        
            cout << "Before modification:" << endl;
            objA.displayData();
        
            objB.modifyClassA(objA); // ClassB modifies private member of ClassA
        
            cout << "After modification:" << endl;
            objA.displayData();
        
            return 0;
        }
                    

Output

Before modification:
Private data of ClassA: 100
After modification:
Private data of ClassA: 150

Pro Tip:

💡 Pro Tip

Friend functions are a powerful tool in C++ when you need a function to access the private members of a class without making it a member of the class. Use them carefully, as they break encapsulation by exposing private data. They should be used sparingly and only when necessary, especially in cases where two or more classes need to closely collaborate.

Use friend classes only when absolutely necessary. Overuse of friendship can lead to tight coupling between classes, making the code harder to test and maintain. Ensure that you follow the principle of least privilege while granting access to private data.