• Articles
  • Tutorials
  • Interview Questions

What is Friend Function in C++? Benefits and Examples

When people learn C++, they often come across many ideas and features that make the language powerful and adaptable. Developers need to know friend functions in C++ to write organized code for classes and objects. Friend functions in C++ are unique and valuable tools that make your code more efficient and flexible. As the name suggests, they are friendly functions. They enhance C++ class flexibility and accessibility.

This blog looks closely at what is friend function in C++, explaining how they are used and their benefits. Let’s embark on a journey to understand the power and purpose of friend functions in C++.

Table of Contents

Check out our YouTube video on C programming language for the absolute beginners

What is Friend Function in C++?

Friend functions in C++ allow external functions or classes to access private and protected members of a class. This can be useful for sharing data between different parts of a program, but it is important to use friend functions carefully to maintain the security and encapsulation of your code.

Think of it as granting permission to trusted outsiders to peek inside a class’s secrets. These friends can manipulate the private data directly, even though they aren’t part of the class itself.

Imagine you have a class that represents a safe with a secret combination. The safe’s combination is private, but you have a trusted friend who is not a member of the family but knows the combination. This friend can open the safe and access its contents when needed. In this analogy, the friend function is like that trusted friend, having access to the private data of the class.

Syntax for Friend Function
friend return_type function_name (arguments);    // for a global function

            or

friend return_type class_name::function_name (arguments);    // for a member function of another class
class intellipaat{
   friend int intellipaat_Function(paat);
   statements;
}

In this example, friendFunction is declared a friend of the MyClass class and can access its private member, privateData. By using ‘friend,’ the compiler recognizes the keyword and knows that the function is a friend function in a C++ program.

Want to jumpstart your career in Computer Programing? Enrol in our C Programming Course and gain your skills to succeed!

What is a Friend Class in C++?

Friend classes in C++ allow one class to access the private and protected members of another class as if it were a member of that class. A friend class can access and change the private data and functions of another class, even though it is a separate class.

Friend classes operate similarly to friend functions, except instead of granting permission to individual functions, they allow entire classes to access the private members of another class. This is helpful when multiple classes need to work closely together, share data, or have a high degree of interaction while still maintaining some level of encapsulation and data hiding. It allows for interaction while keeping some data hidden.

Syntax for Friend Class
friend class class_name;    // declared in the base class
class A{
// intellipaat is a friend class of A
   friend class intellipaat;
}
class intellipaat {
statements;
}

Imagine you have two separate classes, ClassA and ClassB, and you want ClassB to have special access to the private and protected members of ClassA. This is where you can use a friend class. By declaring ClassB a friend of ClassA, you allow ClassB to access ClassA’s private and protected members as if they were its own.

Think of ClassA as a vault with valuable items (private members), and ClassB as a trusted security guard. ClassA wants to keep its items secure, so it only shares its secrets with the security guard, ClassB. This way, ClassB can access and manage the items within the vault while maintaining the privacy and security of ClassA’s belongings.

Learn what a Linear Data Structure is and how it works!

Get 100% Hike!

Master Most in Demand Skills Now !

Characteristics of Friend Functions

  • Not a member of the class it’s friends with.
  • Declared inside the class, defined outside
  • Accesses private and protected class members
  • Can be friends with multiple classes
  • Has global scope and can be called from anywhere
  • Friendship is not inherited.
  • Should be used carefully to avoid breaking encapsulation

How Does Friend Function Work?

To understand it better, here’s an algorithm and a simple flowchart to explain how a friend function works:

Algorithm

  • Declare the friend function inside the class, where it will be given access to private members using the ‘ friend ’ keyword.
  • Define the friend function outside the class as a regular function.
  • Call the friend function from outside the class, passing an object of the class as an argument.
  • Inside the friend function, you can access and manipulate the private and protected members of the class through the passed object.

For example, an overview

#include <iostream>
class Rectangle {
private:
    double length;
    double width;
public:
    Rectangle(double l, double w) : length(l), width(w) {}
    // Declare the friend function inside the class
    friend double calculateArea(const Rectangle& rect);
};
// Define the friend function outside the class
double calculateArea(const Rectangle& rect) {
    return rect.length * rect.width;
}
int main() {
    double length, width;
    std::cout << "Enter the length of the rectangle: ";
    std::cin >> length;
    std::cout << "Enter the width of the rectangle: ";
    std::cin >> width;
    Rectangle rect(length, width);
    // Call the friend function to calculate the area
    double area = calculateArea(rect);
    std::cout << "The area of the rectangle is: " << area << std::endl
    return 0;
}

Output:

Check out C and Data Structure Interview Questions to crack your next interview!

Benefits of Using the Friend Function

  • Enhanced encapsulation control by selectively allowing external access to private members
  • Improved code organization by grouping related functions with a class
  • Efficient access to private data without getter/setter methods
  • Simplified and more readable code for certain operations
  • Flexible design for custom operators or type conversions
  • Easier integration with third-party libraries or external code
  • Reduced overhead compared to making all members public
  • Enhanced maintainability by centralizing access permissions

Applications of the Friend Function 

Here are the top five applications of friend functions in C++:

  1. Operator Overloading: Friend functions are commonly used for overloading operators, such as `+`, ``, `==`, etc., to provide custom behaviors for user-defined types, making complex operations intuitive and efficient.
  2. Accessing Private Members: Friend functions allow controlled access to private and protected members of a class, making them useful for encapsulation while still permitting specific external functions or classes to work closely with an object’s internals.
  3. Type Conversion: Friend functions can define custom type conversion operators (typecasting) between user-defined types, enabling seamless and intuitive type conversions when working with objects of different classes.
  4. Mathematical Classes: In mathematical libraries or classes representing mathematical concepts (e.g., vectors, matrices), friend functions can facilitate advanced mathematical operations that require direct access to private data, ensuring efficiency and code clarity.
  5. Serialization: Friend functions are valuable for serializing and deserializing objects, especially in applications that involve saving or loading complex object structures to/from files or across networks, where direct access to object internals is necessary for efficient data handling.

These applications show how friend functions make code easier to read, maintain, and perform well in C++. They also keep encapsulation and data-hiding principles intact.

Example of a Friend Function in C++

Global Function as Friend Function

#include <iostream>
class MyClass;
// Global function declaration as a friend
void globalFriendFunction(MyClass& obj);
class MyClass {
private:
    int privateVar;
public:
    MyClass(int pv) : privateVar(pv) {}
    // Declare the global function as a friend
    friend void globalFriendFunction(MyClass&);
    void display() {
        std::cout << "Private Var: " << privateVar << std::endl;
    }
};
// Define the global friend function
void globalFriendFunction(MyClass& obj) {
    // Access and manipulate private member of MyClass
    obj.privateVar = 42;
}
int main() {
    MyClass obj(10);
    std::cout << "Before calling global friend function:" << std::endl;
    obj.display();
    // Call the global friend function
    globalFriendFunction(obj);
    std::cout << "After calling global friend function:" << std::endl;
    obj.display();
    return 0;
}

Output:

In this example, we declare a global friend function, ‘globalFriendFunction,‘ that is a friend of ‘MyClass.’ The friend function can access the private ‘member privateVar’ of the class.

Member Function of Another Class as a Friend Function

#include <iostream>
class MyClass; // Forward declaration of MyClass
class FriendClass {
public:
    // Declare FriendClass's member function as a friend
    void friendMemberFunction(MyClass& obj);
};
class MyClass {
private:
    int privateVar;
public:
    MyClass(int pv) : privateVar(pv) {}
    void display() {
        std::cout << "Private Var: " << privateVar << std::endl;
    }
    // Declare FriendClass as a friend
    friend class FriendClass;
};
// Define FriendClass's member function
void FriendClass::friendMemberFunction(MyClass& obj) {
    // Access and manipulate private member of MyClass
    obj.privateVar = 42;
}
int main() {
    MyClass obj(10);
    std::cout << "Before calling friend member function:" << std::endl;
    obj.display();
    FriendClass fc;
    fc.friendMemberFunction(obj);
    std::cout << "After calling friend member function:" << std::endl;
    obj.display();
    return 0;
}

Output:

In this example, ‘FriendClass‘ is another class, and we declare its member function ‘friendMemberFunction‘ as a friend of the  ‘MyClass.’ The friend function can access the private member privateVar of MyClass.

Friend Function Vs. Virtual Function 

Now that we understand what a friend function is let’s explore the key differences between a friend function and a virtual function.

FeatureFriend FunctionVirtual Function
Declarationfriend function_name(parameters);virtual function_name(parameters) = 0;
ScopeOutside the classWithin the class
AccessCan access all members of the class, including private and protected membersCan only access public members of the class
BindingStatic bindingDynamic binding
PolymorphismNot possiblePossible
Use casesTo give non-member functions access to private members of a class, overload operators, and implement algorithms that need to access private membersTo allow derived classes to override the implementation of a function in the base class and implement polymorphism

Conclusion

In C++, a friend function lets a non-member function access private and protected class members. This idea is important because it helps keep class information private while allowing certain functions or classes to access it.

Friend functions have many uses in C++ classes, including custom operators, type conversions, and efficient data access. They are versatile and powerful. It’s important to use them carefully to balance hiding information and making code work well. Also, keep the code organized and easy to understand.

Don’t miss out on the latest programming trends and advancements – be part of Intellipaat’s Community today!

FAQs

How does a friend function differ from a member function?

Friend functions are external to the class and are not bound by the class’s scope. In contrast, member functions are part of the class and have direct access to its members.

Can multiple functions be declared friends in a class?

Yes, a class can have multiple friend functions, allowing several external functions to access its private and protected members.

Are friend functions inherited?

No, If a class inherits from another class, the friend functions of the base class do not become friend functions of the derived class.

Can friend functions access static members?

Yes, friend functions can access both instance and static members of a class, regardless of their access specifiers.

When should I use friend functions?

Use friend functions when you want external functions to work with a class’s private members without making them members of the class itself. This is especially useful for operator overloading and integrating non-member operations.

Course Schedule

Name Date Details
Python Course 20 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 27 Apr 2024(Sat-Sun) Weekend Batch
View Details
Python Course 04 May 2024(Sat-Sun) Weekend Batch
View Details

Full-Stack-ad.jpg