1. Introduction to C++: A Comprehensive Guide with Code Examples - 2023 2. Mastering Data Types in C++: A Comprehensive Guide with Codes and Examples (2023) 3. Learn About Variables and Types of Variables in C++ | Codzify.com 4. Control Statements in C++: A Comprehensive Guide for 2023 5. C++ Tutorial: Understanding Switch Statements with Codes and Examples in 2023 6. Understanding Memory Allocation and Pointers in C++: A Beginners Guide 7. Functions in C++ 8. Call by value and Call by Reference in C++ in depth 9. Array in C++ 10. 2d arrays in C++ 11. Classes and Objects in C++ 12. Static Functions in C++ 13. Constructors and Destructors in C++ - A Complete Guide with Examples 14. Mastering Copy Constructor in C++ - Shallow vs Deep Copy with Examples | Codzify 15. Understanding Friend Functions in C++ Made Simple! 16. Inline Functions in C++ 17. this Pointer in C++ 18. Mastering Inheritance in C++: Types and Examples Explained 19. Types of Inheritance in C++ 20. Polymorphism in C++ Explained with Codes and Examples in 2023 21. Templates in C++ 22. Getting the Value of a MultiMap in C++: Step-by-Step Guide with Examples 23. Multimap Find and Replace Operator in C++: Step-by-Step Guide - Codzify Topics 24. Exploring the Next_Permutation Algorithm without STL in C++ - Codzify Topics 25. C++ - The Difference Between Map and HashMap in STL 26. Updating Values in a std::multimap in C++ - Codzify Topics 27. Which data structure sorts the elements on insertion in C++ STL? 28. Can we implement Red Black Tree in c++ by STL containers? 29. How to Dynamically Declare an Array of Objects with a Constructor in C++ - A Step-by-Step Guide 30. What is the difference between a pointer and an object in C++? 31. Mastering Red-Black Trees with STLs Internal Implementation: A Step-by-Step Guide

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.

Watch Video Tutorials at Codzify YouTube Channel:

Codzify Logo

Terms and Conditions    Cookie Policy   Refund Policy   Adsense Disclaimer

Contact: teamcodzify@gmail.com