Blog Blog Posts Business Management Process Analysis

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

This blog looks closely at friend functions, explaining what they are, 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

{
“@context”: “https://schema.org”,
“@type”: “VideoObject”,
“name”: “C Programming for Beginners | C Programming Tutorial | Learn C | Intellipaat”,
“description”: “What is Friend Function in C++? Benefits and Examples”,
“thumbnailUrl”: “https://img.youtube.com/vi/iT_553vTyzI/hqdefault.jpg”,
“uploadDate”: “2023-09-22T08:00:00+08:00”,
“publisher”: {
“@type”: “Organization”,
“name”: “Intellipaat Software Solutions Pvt Ltd”,
“logo”: {
“@type”: “ImageObject”,
“url”: “https://intellipaat.com/blog/wp-content/themes/intellipaat-blog-new/images/logo.png”,
“width”: 124,
“height”: 43
}
},
“embedUrl”: “https://www.youtube.com/embed/iT_553vTyzI”
}

What is a Friend Function in C++?

The friend function is a way to give special access privileges to functions or classes that aren’t part of a class but need to access its private or protected data. In C++, a friend function lets external functions or classes access private and protected members of a class. Program parts can share data, but it is controlled to keep it secure and encapsulated.

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++?

In C++, a friend class can 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!

Characteristics of Friend Functions

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

For example, an overview

#include 
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

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 
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 
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.

Feature Friend Function Virtual Function
Declaration friend function_name(parameters); virtual function_name(parameters) = 0;
Scope Outside the class Within the class
Access Can access all members of the class, including private and protected members Can only access public members of the class
Binding Static binding Dynamic binding
Polymorphism Not possible Possible
Use cases To give non-member functions access to private members of a class, overload operators, and implement algorithms that need to access private members To 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?

Friendships are not inherited. 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.

The post What is Friend Function in C++? Benefits and Examples appeared first on Intellipaat Blog.

Blog: Intellipaat - Blog

Leave a Comment

Get the BPI Web Feed

Using the HTML code below, you can display this Business Process Incubator page content with the current filter and sorting inside your web site for FREE.

Copy/Paste this code in your website html code:

<iframe src="https://www.businessprocessincubator.com/content/what-is-friend-function-in-c-benefits-and-examples/?feed=html" frameborder="0" scrolling="auto" width="100%" height="700">

Customizing your BPI Web Feed

You can click on the Get the BPI Web Feed link on any of our page to create the best possible feed for your site. Here are a few tips to customize your BPI Web Feed.

Customizing the Content Filter
On any page, you can add filter criteria using the MORE FILTERS interface:

Customizing the Content Filter

Customizing the Content Sorting
Clicking on the sorting options will also change the way your BPI Web Feed will be ordered on your site:

Get the BPI Web Feed

Some integration examples

BPMN.org

XPDL.org

×