×

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++ int into String

Data type conversion is a standard editing process. You may need to convert variable from one type of data to another in a variety of situations. There are two ways...

5 minutes read.

Decimal to Binary in C++

What is the meaning of Decimal Numbers? Decimal numbers range from 0 to 9, there are a total of ten digits between 0 and 9. Any number with more than two...

3 minutes read.

Difference between Two Sets in C++

The distinction between the two sets is made up of the components that are present in the first set but absent from the second set. The function consistently duplicates the...

3 minutes read.

Pthread in C++ Parameters

Pthreads, also known as POSIX threads, is a POSIX standard for multithreading in C/C++. It allows a program to control multiple different threads of execution concurrently. Using pthreads, you can create...

4 minutes read.

How to create a stack in C++

A stack is a data structure, which is of linear type. A specific order has to be followed while inserting and deleting the elements from the stack. Generally, stack follows...

5 minutes read.

Factorial of a Number in C++ using while Loop

What is a factorial? The factorial of a number is the product of all the positive numbers less than or equal to n, indicated by n! According to the standard for an...

6 minutes read.

Program to find the GCD of two numbers in C++

Before understanding the program of GCD or HCF, one must know what GCD or HCF is. What is GCD? The GCD is referred to as Greatest Common Divisor. HCF is the other...

8 minutes read.

C++ Multimap

Definition: In C++, a multimap is similar to a map with the additional concept, where multiple elements possess the same keys. It is also not necessary that the key values and...

4 minutes read.

Loops in C++

A loop statement in most programming languages allows us to execute a statement or a collection of statements numerous times. Control structures of programming languages vary, allowing for more complex...

6 minutes read.

C++ Memory Management

Memory management is a method of controlling computer memory and allocating memory space to applications to increase overall system performance. What is the purpose of memory management? Because the array contains homogeneous...

4 minutes read.

Decimal to Octal in C++

We must create a software that converts a decimal number into an equal octal number given a decimal number as input i.e. convert a number having a base value of...

3 minutes read.

Call by Pointer in C++

What is Pointer? Every variable in C++ has a specific address or location in the computer's memory, and this address is known as the memory address. A pointer can be defined...

5 minutes read.

C++ Type Casting

The type casting of variables in the C++ programming language will be covered in this section. The term "type casting" describes how software converts one data type to another. There...

9 minutes read.

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++

Precision of floating point numbers Using these functions floor(), ceil(), trunc(), round() and setprecision() in C++ 1/2 decimal equal is 0.555555555555555555555 .... An indefinite number of lengths will require the storage...

4 minutes read.

Static keyword in C++ vs Java

Both in C++ and Java, the static keyword is employed for essentially the same function. But there are some variations. The static keyword's similarities and differences between C++ and Java...

3 minutes read.

Singleton Design Pattern in C++

Singleton is similar to the global variable. Singleton helps to have only one object of its kind and provides only single access. One of the key features of the singleton...

2 minutes read.

This keyword in C++

This keyword in C++ is a pointer which points to the object. It is passed as an argument to functions which helps in accessing the object. It is used for a...

3 minutes read.

Templates in C++ vs Generics in Java

As the title suggests, there is no rivalry or there is no cut comparison between generics and templates in Java and C++, respectively. The main aim of this article is...

4 minutes read.

C++ Reading file

In file handling, read() function is used to read data from the file into the program. The read() uses ifstream library to read data from a file. Syntax file-stream-class   file-stream-object;   file-stream-object.read((char *)&var , sizeof (var)); <h3">Example ofstream  outfile;         outfile . read((char*)&emp,sizeof(emp)); C++ File Handling read() Function Example Reading the content of existing...

2 minutes read.

Const Keyword in C++

The const programming language keyword will be covered in this section. The constant value that cannot change during program execution is defined using the const keywords. It implies that once...

9 minutes read.