Understanding Friend Functions in C++ Made Simple!

Article by: Manish Methani

Last Updated: October 17, 2021 at 2:04pm IST
5 min 9 sec

Table of Contents:

Introduction to Friend Functions

Do you need to access private members of an object from outside its class? Well, introducing the friend function! It's a special function capable of accessing private or protected members of an object. This function is 'friends' with a class and can be called with an object as an argument.

Friend Functions in C++

Let's break it down with some examples to understand this concept better:

Program without Using Friend Function (Before Scenario)

Consider the following code:

#include <iostream>
using namespace std;

class Demo {
    int firstNumber, secondNumber; // private data members
public:
    Demo(int a, int b) {
        firstNumber = a;
        secondNumber = b;
    }
    
    void add(Demo);
};

// Function attempting to access private members (Error Scenario)
void add(Demo demoInstance) {
    int c = demoInstance.firstNumber + demoInstance.secondNumber;
    cout << "Addition is " << c;
}

int main() {
    Demo a(12, 13);
    add(a);
    return 0;
}

Running this code would result in a compilation error stating that 'firstNumber' and 'secondNumber' are private members of 'Demo'. This shows that accessing private members directly from outside the class isn't allowed.

Program Using Friend Function (After Scenario)

Now, let's modify the code to use a friend function:

#include 
using namespace std;

class Demo {
    int firstNumber, secondNumber; // private data members
public:
    Demo(int a, int b) {
        firstNumber = a;
        secondNumber = b;
    }
    
    friend void add(Demo); // Declare 'add' function as a friend
};

// Friend function that accesses private members
void add(Demo demoInstance) {
    int c = demoInstance.firstNumber + demoInstance.secondNumber;
    cout << "Addition is " << c;
}

int main() {
    Demo a(12, 13);
    add(a);
    return 0;
}

Here, we've made the add() function a friend of the Demo class. This allows add() to access the private members firstNumber and secondNumber. When running the program, it should display:

Addition is 25

This showcases how using a friend function allows accessing private members from outside the class, enabling operations that would otherwise result in compilation errors.

Understanding friend functions in C++ enables better control over data accessibility within classes and facilitates smooth handling of private members when required.

FAQ

1. What is a friend function in C++?

A friend function in C++ is a function that has access to the private and protected members of a class. It is not a member of the class, but it is granted access to its private or protected members.

2. How is a friend function declared?

To declare a friend function in C++, the keyword "friend" is used in the class declaration followed by the function prototype. This grants access to the private members of the class to that function.

3. Can friend functions access all the private members of a class?

Yes, friend functions can access both private and protected members of a class in C++. They are not restricted to accessing only one type of member.

4. What are the advantages of using friend functions?

Friend functions provide additional flexibility and functionality in handling classes by allowing external functions to access private members. They enable more controlled and specific access to class internals without violating encapsulation.

5. When should I use friend functions?

Friend functions are useful when specific operations or algorithms need direct access to private or protected members of a class. They are beneficial in scenarios where it enhances the design and usability of the code.

Simplified Coding for Beginners.








Download the Codzify
Mobile App


Mobile App Development, Web App Development, Programming Languages, Latest Tech News & lot more.

Codzify Mobile App

A self-paced learning Courses Created by an Engineer
For Engineers.

Premium

The Complete Angular Course

Instructor: Manish Methani

Explore Curriculum
Free

C Programming for Absolute Beginners

Instructor: Manish Methani

Start Watching
Premium

Flutter Mobile App Development Course

Instructor: Manish Methani

Explore Curriculum
Free

Learn HTML, CSS & Bootstrap

Instructor: Manish Methani

Start Watching

Test your skills with these expert-led curated
Mock Tests.

C Programming Test

Test your C Programming skills with this comprehensive mock test on C Programming.

Take Test

Flutter Test

Solve most asked Interview Questions on Flutter and Test your foundational skills in flutter.

Take Test

GATE(CSE) Operating Systems

Solve most asked GATE Questions in Operating Systems and test your Gate Score.

Take Test

HTML,CSS Test

This is a mock test designed to help you assess your knowledge and skills in HTML and CSS.

Take Test

(GATE CSE) Data Structures & Algorithms Test

Solve most asked GATE Questions in Data Structures and Algorithms and test your Gate Score.

Take Test
include_once 'codzify-footer.php'; ?>