Browse by Domains

Friend Function in C++ and classes with Examples -2024

Introduction

In the domain of C++ programming, understanding the concept of friend functions is crucial for mastering classes and their interactions.

In this blog, we delve into the essence of friend functions in C++, exploring what they are, their significance, and how they operate within the framework of classes.

If you’re wondering, “What is friend function in C++?” or seeking clarity on the workings of C++ friend class, you’ve come to the right place.

Through clear explanations and illustrative examples, we’ll demystify the role of friend functions and classes, empowering you to use them effectively in your C++ projects.

What is a Friend Function in C++?

In C++, a friend class allows one Class to access another class’s private and protected members. This means that the friend class can access the private and protected members of the Class, and it is declared as a friend, just like a member function of that Class.

Syntax

class ClassName1 {
    // Class definition

    friend class ClassName2; // Declaration of friend class
};

class ClassName2 {
    // Class definition
};

In this syntax:

  • friend class ClassName2; declares ClassName2 as a friend class of ClassName1.
  • This declaration allows ClassName2 to access the private and protected members of ClassName1.
  • After the friend keyword, ClassName2 is specified, indicating that ClassName2 has access to ClassName1‘s private and protected members.

Example of C++ Code using Friend Class

#include <iostream>
using namespace std;

class ClassB; // Forward declaration of ClassB

class ClassA {
    private:
        int numA;
    public:
        ClassA() : numA(0) {}

        // Friend class declaration
        friend class ClassB;

        void display() {
            cout << "ClassA: " << numA << endl;
        }
};

class ClassB {
    private:
        int numB;
    public:
        ClassB() : numB(0) {}

        void setValue(ClassA& objA, int value) {
            objA.numA = value; // Accessing private member of ClassA
        }

        void display(ClassA& objA) {
            cout << "ClassB: " << numB << endl;
            objA.display(); // Accessing ClassA's member function
        }
};

int main() {
    ClassA objA;
    ClassB objB;

    objB.setValue(objA, 100);
    objB.display(objA);

    return 0;
}

Output

ClassB: 0
ClassA: 100

Explanation

  • In this example, we have two classes: Class A and Class B.
  • ClassB is declared a friend class inside ClassA, which allows ClassB to access ClassA’s private member numA.
  • Inside ClassB, the setValue function modifies the private member numA of ClassA directly, demonstrating the friend class’s ability to access private members.
  • The display function of ClassB also accesses ClassA’s member function display, demonstrating that friend classes can also access member functions of the Class they are friends with.
  • In the main function, objB calls setValue to modify objA.numA to 100, and then objB.display is called to display both numB and numA.

Learners Tip: Friend classes or functions have the flexibility to be declared within any segment of the base class body, irrespective of its designation as private, protected, or public. This rule applies consistently across all declarations.

Join our “Introduction to C++” course today and learn how to become a proficient C++ developer!

Define Friend Function In C++

A friend function in C++ is a non-member function that has access to a class’s private and protected members. This means that a friend function can manipulate a class’s private and protected members as if it were a member function of that Class.

Here is the friend function in C++ syntax to refer

Syntax

class ClassName {
    private:
        // Private members
    public:
        // Public members

        friend return_type functionName(parameters); // Declaration of friend function
};

return_type functionName(parameters) {
    // Function definition
}

In the syntax above:

  • The friend keyword precedes the declaration of the friend function inside the Class.
  • return_type specifies the data type returned by the friend function.
  • functionName is the name of the friend function.
  • Parameters are the variables passed to the function as arguments.

By declaring a function as a friend of a class, that function gains access to all private and protected class members, enabling it to operate on them directly. This concept is beneficial in scenarios where a function needs access to class members but isn’t logically a class member.

Also, explore “C++ Inheritance” and learn how to extend the functionality of your classes effortlessly!

The Different Types Of C++ Friend Functions

1. Global function

Global function as a friend function in C++ is declared outside of any class but granted access to a class’s private and protected members through the friend keyword. This allows the global function to manipulate these members as if it were a class member function.

Why we use it?

  • Global functions, such as friend functions, are handy when a function needs access to private or protected members of a class but doesn’t logically belong to that Class.
  • They promote encapsulation by providing controlled access to class internals without exposing them through public member functions.

Example of declaring a global function as a friend function in C++:

#include <iostream>
using namespace std;

class MyClass {
    private:
        int num;

    public:
        MyClass() : num(10) {}

        friend void globalFunction(MyClass obj); // Declaration of global function as friend
};

void globalFunction(MyClass obj) {
    cout << "Accessing private member of MyClass: " << obj.num << endl;
}

int main() {
    MyClass obj;
    globalFunction(obj);

    return 0;
}

Output

Accessing private member of MyClass: 10

Detailed Explanation

  • In the example, MyClass contains a private member num.
  • The global function globalFunction is declared a friend of MyClass, allowing it to access MyClass’s private member num.
  • Inside globalFunction, we can directly access MyClass’s private member num using an object of MyClass.
  • In the main function, an object obj of MyClass is created and passed to globalFunction, demonstrating how the global function accesses the private member of MyClass.
  • The output confirms that globalFunction successfully accessed and displayed the private member num of MyClass.

“Get hands-on experience with these practical C++ Projects To Work On In 2024 and sharpen your skills!”

2. Member Function of Another Class as Friend Function

A member function of another class as a friend function in C++ refers to a scenario where a member function of one Class is declared a friend of another. This grants the friend member function access to the private and protected members of the Class, which is declared as a friend of, just like a member function of that Class.

Why we use it?

  • It enables specific member functions of one Class to access private or protected members of another class, fostering controlled interaction between classes.
  • This approach is practical when certain functionalities of one Class require direct access to the internals of another class, promoting encapsulation and modularity.

Example of declaring a member function of another class as a friend function in C++:

#include <iostream>
using namespace std;

class ClassB; // Forward declaration of ClassB

class ClassA {
    private:
        int numA;

    public:
        ClassA() : numA(0) {}

        // Declaration of ClassB's member function as a friend function
        friend void ClassB::display(ClassA objA);
};

class ClassB {
    public:
        void display(ClassA objA) {
            cout << "Accessing private member of ClassA from ClassB: " << objA.numA << endl;
        }
};

int main() {
    ClassA objA;
    ClassB objB;

    objB.display(objA);

    return 0;
}

Output

Accessing private member of ClassA from ClassB: 0

Explanation

  • In this example, ClassA contains a private member numA.
  • ClassB’s member function display is declared a friend of ClassA inside ClassA.
  • This declaration allows ClassB display access to ClassA’s private member number.
  • In the main function, an object objA of ClassA and an object objB of ClassB are created.
  • When objB.display(objA) is called, ClassB display successfully accesses and displays the private member numA of objA.

More Examples of C++ Friend Function in Use

Here are more examples to explain the friend function with examples in C++:

Example 1: Friend Function to Calculate Average

#include <iostream>
using namespace std;

class AverageCalculator {
    private:
        int num1, num2;
    public:
        AverageCalculator(int a, int b) : num1(a), num2(b) {}

        // Friend function to calculate average
        friend float calculateAverage(AverageCalculator obj);
};

// Definition of friend function
float calculateAverage(AverageCalculator obj) {
    return (float)(obj.num1 + obj.num2) / 2;
}

int main() {
    AverageCalculator obj(10, 20);
    cout << "Average: " << calculateAverage(obj) << endl;
    return 0;
}

Output

Average: 15

Explanation: Here, calculateAverage is declared as a friend function of AverageCalculator, allowing it to access num1 and num2 directly to calculate the average.

Example 2: Friend Function for Matrix Addition

#include <iostream>
using namespace std;

class Matrix {
    private:
        int mat[2][2];
    public:
        Matrix() {
            cout << "Enter 4 matrix elements: ";
            for (int i = 0; i < 2; ++i)
                for (int j = 0; j < 2; ++j)
                    cin >> mat[i][j];
        }

        // Friend function for matrix addition
        friend Matrix addMatrices(Matrix m1, Matrix m2);
        
        void display() {
            cout << "Matrix:" << endl;
            for (int i = 0; i < 2; ++i) {
                for (int j = 0; j < 2; ++j)
                    cout << mat[i][j] << " ";
                cout << endl;
            }
        }
};

// Definition of friend function
Matrix addMatrices(Matrix m1, Matrix m2) {
    Matrix result;
    for (int i = 0; i < 2; ++i)
        for (int j = 0; j < 2; ++j)
            result.mat[i][j] = m1.mat[i][j] + m2.mat[i][j];
    return result;
}

int main() {
    Matrix m1, m2, sum;
    sum = addMatrices(m1, m2);
    sum.display();
    return 0;
}

Output

Matrix:
5 7 
9 11

Explanation: Here, addMatrices is declared a friend function of Matrix, enabling it to access the private member mat of m1 and m2 to perform matrix addition.

Example 3: Friend Function for Increment

#include <iostream>
using namespace std;

class Number {
    private:
        int value;
    public:
        Number(int v) : value(v) {}

        // Friend function for increment
        friend Number increment(Number num);
        
        void display() {
            cout << "Value: " << value << endl;
        }
};

// Definition of friend function
Number increment(Number num) {
    num.value++;
    return num;
}

int main() {
    Number num(5);
    num.display();
    num = increment(num);
    num.display();
    return 0;
}

Output

Value: 5
Value: 6

Explanation: In this example, increment is declared as a friend function of Number, allowing it to modify the private member value to increment the number directly.

Example 4: Function Friendly to Multiple Classes

#include <iostream>
using namespace std;

class ClassB; // Forward declaration of ClassB

class ClassA {
    private:
        int numA;
    public:
        ClassA(int num) : numA(num) {}

        // Friend function friendly to ClassA and ClassB
        friend void displayBoth(ClassA objA, ClassB objB);
};

class ClassB {
    private:
        int numB;
    public:
        ClassB(int num) : numB(num) {}

        // Friend function friendly to ClassA and ClassB
        friend void displayBoth(ClassA objA, ClassB objB);
};

// Definition of the friend function
void displayBoth(ClassA objA, ClassB objB) {
    cout << "From ClassA: " << objA.numA << endl;
    cout << "From ClassB: " << objB.numB << endl;
}

int main() {
    ClassA objA(10);
    ClassB objB(20);
    displayBoth(objA, objB);
    return 0;
}

Output

From ClassA: 10
From ClassB: 20

Explanation

  • In this example, we have classes A and B, each with a private member.
  • The function displayBoth has declared a friend to both ClassA and ClassB, allowing it to access both classes’ private members, numA and numB.
  • In the main function, objects objA and objB of ClassA and ClassB are created, respectively.
  • The displayBoth function is called with objA and objB as arguments, demonstrating how a single function can access private members of multiple classes.

Learners Tips

The sequence in which the friend function is declared concerning another class is critical and necessitates careful consideration. It is vital to establish both classes before defining the function, thus prompting the Use of out-of-class function definition.

Furthermore, read “C++ Functions” now to see how functions contribute to code organization and reusability in C++!

Advantages of Friend Functions

  • Versatility in Overloaded Operators: Friend functions allow overloaded operators to access private members of a class, enhancing flexibility in defining custom behavior for operators like +, -, etc.
  • Interclass Interactions: Friend facilitates seamless communication between different classes by granting access to private and protected members, promoting modularity and encapsulation.
  • Serialization: friend function C++ plays a vital role in serialization, enabling classes to efficiently serialize and deserialize their private data without compromising encapsulation.
  • Type Conversion: Friend functions enable type conversion by accessing private members. This allows for smooth conversion between different data types, enhancing code flexibility and readability.
  • Domain-Specific Language: Friend functions empower developers to create domain-specific languages within C++ programs, enhancing expressiveness and readability by enabling custom syntax and semantics.

Disadvantages of Friend Functions:

  • Limited Polymorphism: Friend functions are not polymorphic, limiting their usage in scenarios requiring dynamic behavior based on the object’s runtime type.
  • Inheritance: Friend functions can’t access private members of derived classes, potentially complicating inheritance hierarchies and violating the principle of least privilege.
  • Code Complexity: Excessive Use of friend functions can lead to increased code complexity and reduced maintainability due to tight coupling between classes and functions. It can also hinder code comprehension and debugging.

Accelerate your C++ programming skills with our curated selection of top book recommendations designed to accelerate your learning curve.

Wrapping Up

Through this exploration, you’ve gained insights into the significance and syntax of friend method C++, understanding their role in enabling interactions between classes while maintaining encapsulation.

Whether you’re just starting to grasp the fundamentals or seeking to deepen your expertise in C++ programming, exploring Great Learning’s free C++ tutorial and software engineering course can be immensely beneficial.

Our resources offer a structured pathway from understanding the basics of friend functions in C++ to mastering advanced concepts, empowering you with invaluable skills for software engineering endeavors.

Join Great Learning‘s community of learners and master C++ programming today.

FAQs

Q: Can a friend function be declared within a class?

A: No, a friend function C++, cannot be declared within a class. Friend functions are declared outside the Class but can be granted access to its private and protected members through a declaration inside the Class using the friend keyword.

Q: Can friend functions be defined inside a namespace?

A: Yes, friend functions can be defined inside a namespace. They can be declared as friends of classes within the same namespace or outside the namespace. Defining friend functions inside a namespace allows for better organization and encapsulation of related functionalities.

Q: Can friend functions be declared in a header file?

A: Yes, friend functions can be declared in a header file like any other function. When declaring a friend function in a header file, it provides visibility to different source files that include the header file, allowing them to access the private and protected members of the Class. However, the friend function definition should be implemented in a source file (.cpp) to avoid multiple definition errors.

Q: Can a friend function be virtual?

A: No, friend functions cannot be virtual. Virtual functions are member functions of a class and participate in dynamic dispatch, which allows them to be overridden in derived classes. On the other hand, friend functions are not members of a class and do not participate in polymorphism.

Q: Do derived classes inherit friend functions?

A: No, friend functions are not inherited by derived classes. Inheritance in C++ does not affect friend relationships. Each Class must explicitly declare friend functions if they need access to private or protected members.

Avatar photo
Great Learning Team
Great Learning's Blog covers the latest developments and innovations in technology that can be leveraged to build rewarding careers. You'll find career guides, tech tutorials and industry news to keep yourself updated with the fast-changing world of tech and business.

Leave a Comment

Your email address will not be published. Required fields are marked *

Great Learning Free Online Courses
Scroll to Top