×

C++ Friend Functions

In C++, friends are special functions that are not a part of a class yet have access to its private and protected members. The friend keyword is used to declare such a function inside the class.

Friend functions are useful when we need to grant secret data access to other functions (or other classes) without explicitly revealing it.

Key Points:

  • It is specified inside a class using the buddy keyword.
  • Defined outside of the class as an ordinary function.
  • It can get in touch with protected and private class members.
  • Since it is not considered a member of the class, it is called a normal function.

Algorithm:

Below are the different steps need to be followed by the friend function in C++:

  • Define a class with private members.
  • Declare a friend function inside the class using the friend keyword.
  • Define the friend function outside the class.
  • Create an object of the class in main().
  • Call the friend function, passing the class object as an argument.
  • Access and manipulate private data within the friend function.

Pseudo code:

START

1. Define a class ‘MyClass’

2. Declare a private data member ‘data’

3. Create a public constructor to initialize ‘data’

4. Declare a friend function ‘displayData(obj)’ inside the class

   - This function will access private members

5. Define the friend function ‘displayData(obj)’ outside the class

   - Print the value of ‘data’

6. In ‘main()’ function:

   a. Create an object ‘obj’ of ‘MyClass’ and initialize it

   b. Call ‘displayData(obj)’, passing the object

7. The friend function accesses and displays the private data

END

Example 1:

Let us take an example to illustrate the Friend Function in C++.

#include <iostream>

using namespace std;

class MyClass {

private:

    int data; // Private member

public:

    // Constructor to initialize private data

    MyClass(int value) : data(value) {}

    // Friend function declaration

    friend void displayData(const MyClass& obj);

};

// Friend function definition (outside the class)

void displayData(const MyClass& obj) {

    // Accessing private member of MyClass

    cout << "Private Data: " << obj.data << endl;

}

int main() {

    MyClass obj(10); // Creating object with value 10

    displayData(obj); // Calling friend function

    return 0;

}

Output:

Private Data: 10

Explanation:

  • Member of Private Data: MyClass is a class that contains private integer data.
  • Declaration of the Friend Function: The displayData() is declared as a friend function inside MyClass.
  • What the Friend Function Is: It has data access capabilities and is defined outside of the class.
  • Object Creation: The displayData(obj) is called following the creation of an object, obj, in main().
  • Accessing Private Data: Once the function has successfully obtained access to the private data, it prints the contents.

Example 2:

Let us take another example using a friend function to Add Two private Data Members from Different classes in C++.

#include <iostream>

using namespace std;

class ClassB; // Forward declaration

class ClassA {

private:

    int numA;

public:

    // Constructor to initialize numA

    ClassA(int value) : numA(value) {}

    // Friend function declaration

    friend int addNumbers(const ClassA& objA, const ClassB& objB);

};

class ClassB {

private:

    int numB;

public:

    // Constructor to initialize numB

    ClassB(int value) : numB(value) {}


    // Friend function declaration

    friend int addNumbers(const ClassA& objA, const ClassB& objB);

};

// Friend function definition (outside both classes)

int addNumbers(const ClassA& objA, const ClassB& objB) {

    return objA.numA + objB.numB; // Accessing private members

}

int main() {

    ClassA objA(5);  // Object of ClassA with value 5

    ClassB objB(10); // Object of ClassB with value 10

    cout << "Sum: " << addNumbers(objA, objB) << endl; // Calling friend function

    return 0;

}

Output:

Sum: 15

Explanation:

  • Two classes (Class A and Class B) have private data members (numA and numB).
  • The Friend Function (addNumbers()) is defined by both classes.
  • Friend’s function’s definition: It obtains the sum of each classes’ private data members.
  • Creation of Objects: Both classes’ objects are created and initialized with values by Main().
  • Call to Function: addNumbers(objA, objB) calculates the sum of numA and numB.

Usage of Friend Functions:

  • When an external function needs access to private data.
  • When some operators (like operator+ and operator<<) are overloaded.
  • When two or more classes need to communicate sensitive information.

Conclusion:

In conclusion, the friend function is a useful feature in C++ that allows outside functions to access a class’s private and protected members without actually being a part of that class. It is declared inside the class using the friend keyword and defined outside of it, just like any other function. Friend functions are very helpful for activities like operator overloading and inter-class communication that need access to secret information. However, using buddy functions excessively can undermine encapsulation and reduce the maintainability of code. In order to balance data security with flexibility, they should be utilized rarely. Programmers can write more organized and efficient C++ programs by controlling access to class members by understanding buddy functions.


Related Topics

C++ References

C++ References An alias is a reference variable that is another name for a variable already in existence. If a relation is initialized with a variable, it is possible to use...

3 minutes read.

C++ Close file

C++ File Handling close() Function A file which is opened while reading or writing in file handling must be closed after performing an action on it. The close() function is used to close...

2 minutes read.

C++ Inline function

A C++ function that extends in line when called is known as an inline function. It reduces function call overhead by having the compiler use the function code rather than...

4 minutes read.

C++ Polymorphism

Polymorphism refers to the fact that something exists in several forms. Polymorphism, in simple terms, is the ability of a message to be presented in several formats. A real-life example...

4 minutes read.

C++ Forward Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

Reserved Keywords in C++

What are reserved keywords in C++? There are a few keywords that cannot be used as identifiers as those words are reserved for some other purposes, such keywords are called reserved...

15 minutes read.

What are local class and global class in C++

In C++, a class is a fundamental block that achieves object-oriented programming. The class holds its data members and member functions. Objects help to access the data elements and functions....

4 minutes read.

std::min in C++

std::min in C++ std::min is specified in the program code, used to calculate the lowest amount that has been transferred. When there's more of someone who returns first of them. It's used...

2 minutes read.

Roadmap to C++ Programming

Introduction There are so many programming languages available in the market, but among them, C++ is something that never lost its charm. It has a powerful impact on the programming world....

4 minutes read.

How to find the length of the vector in C++

Like dynamic arrays, vectors can automatically adjust their size when an element is added or removed, and the container manages its storage. Because vector items are stored in contiguous storage, iterators...

3 minutes read.

How to build a program in C++

Building a program is all about creating the program and executing it successfully. There are some steps  precisely, which must be followed to make the program. Step 1: Get an IDE...

4 minutes read.

C++ If-else-if

Introduction: If-else-if control statement is an if statement used with an optional else if control statement to check multiple conditions. In this control statement, when any one of the condition returns...

4 minutes read.

Programs to Print Pyramid Patterns in C++

We will explore how to use code to print a variety of patterns utilizing stars (*), numbers (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,.…)  and alphabets...

7 minutes read.

Abstract class in C++

In this article, you will get exposure to an abstract class in C++. We will discuss this topic using some practical examples too. To understand the abstract classes, you should...

6 minutes read.

C++ Bidirectional Iterators

Iterators : Iterators serve as a link between algorithms and STL containers, allowing the data inside the container to be modified. They let you to iterate through the container, access and...

3 minutes read.

C++ Algorithms

There are plenty of programming paradigms that are closely associated with the implementations of code and simulate them into a proper functional one. This is done with the help of...

5 minutes read.

Learn C++ Tutorial

C++ Introduction C++ is an object-oriented programming language. It was developed by Bjarne Stroustrup at AT&T Bell Laboratories. It is superset (extension) of C programming language. Depending upon features supported by programming...

10 minutes read.

C++ program to read string using cin.getline()

C++ program to read string using cin.getline() C++ getline() is a standard library feature for reading a string or a line from an input source. A getline() function gets characters from...

3 minutes read.

C++ Ternary Operator

In this tutorial, we'll learn about the C++ ternary operator and how to utilise it to manage the program's flow using examples. Ternary Operator: The if-else statement and the conditional operator use...

3 minutes read.

INT_MAX and INT_MIN in C/C++

In competitive programming, assigning a variable that maximum or minimum value a data type can carry is frequently necessary. Still, it might be challenging to recall such a significant, exact...

3 minutes read.