Understanding the Friend Function in C++ (With Example)

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

In the dynamic realm of programming, C++ stands tall as a versatile language, continually sought after by professionals ranging from software developers to game designers and backend engineers. Holding a reliable reputation, C++ boasts a rich feature set, including the intriguing concept of friend functions. In C++, a friend function is a unique entity defined outside the class’s boundaries yet bestowed with the remarkable authority to access both protected and private members of the class it befriends. Despite not being a member function itself, the prototype of a friend function finds its home within the class declaration, showcasing the language’s elegance and flexibility. 

 

This capability isn’t limited solely to classes; it expands its scope to encompass class templates, function templates, and even standard functions and member functions, affirming its status as a potent asset in the toolkit of C++ developers. The TIOBE index of 2022 underscores C++’s prominence as the fourth most widely used language worldwide, underscoring its enduring significance and broad acceptance in the constantly evolving realm of technology.

 

What is the Friend Function in C++?

 

In C++, the friend function is declared outside the class’s scope, granting it access to both protected and private members of the class. While not a member function, the prototypes for friend functions are specified within the class declaration. This encompasses class templates, classes, function templates, functions, and member functions, allowing the friend function to access all members of the class.

 

Use of Friend Class in C++

 

The friend class offers various advantages and applications. Some key scenarios include:

 

  • Accessing private and protected members from other classes, as you’re likely aware.
  • Designating all functions of a class as friend functions.
  • Facilitating extension of storage and access to its components while preserving encapsulation.
  • Permitting classes to exchange information about private members.
  • Commonly employed when multiple classes have interconnected data members.

 

Friend Functions in C++ Types

 

In C++, friend functions come in the following variations:

 

  1. Function with no arguments and no return value.
  2. Function with no arguments but with a return value.
  3. Function with arguments but no return value.
  4. Function with arguments and a return value.

 

DevOps & Cloud Engineering
Internship Assurance
DevOps & Cloud Engineering

Syntax of Implementing Friend Class in C++

 

The syntax for implementing a friend class is as follows:

 

class ClassB;

 

class ClassA {

 

   // ClassB is a friend class of ClassA

 

   friend class ClassB;

 

   … .. …

 

}

 

class ClassB {

 

   … .. …

 

}

 

As evident from the syntax, simply prepend the keyword ‘friend’ before a class to designate it as a friend class. Employing this syntax will establish ClassB as a friend class of ClassA. As ClassB assumes the role of a friend class, it gains access to all public, private, and protected members of ClassA. Conversely, the reverse is not applicable. This is because C++ permits only the granting of the friend relationship, not its reciprocation. Consequently, ClassA won’t be able to access the private members of ClassB.

 

Friend Function in C++ with Example

 

Let’s see the simple example of the C++ friend function used to print the length of a box.

 

#include <iostream>    

using namespace std;    

class Box    

{    

    private:    

        int length;    

    public:    

        Box(): length(0) { }    

        friend int printLength(Box); //friend function    

};    

int printLength(Box b)    

{    

   b.length += 10;    

    return b.length;    

}    

int main()    

{    

    Box b;    

    cout<<“Length of box: “<< printLength(b)<<endl;    

    return 0;    

}    

 

Output:

 

Length of box: 10  

Let’s see a simple example when the function is friendly to two classes.

 

#include <iostream>  

using namespace std;  

class B;          // forward declaration.  

class A  

{  

    int x;  

    public:  

    void setdata(int i)  

    {  

        x=i;  

    }  

    friend void min(A,B);         // friend function.  

};  

class B  

{  

    int y;  

    public:  

    void setdata(int i)  

    {  

        y=i;  

    }  

    friend void min(A,B);                    // friend function  

};  

void min(A a,B b)  

{  

    if(a.x<=b.y)  

    std::cout << a.x << std::endl;  

    else  

    std::cout << b.y << std::endl;  

}  

   int main()  

{  

   A a;  

   B b;  

   a.setdata(10);  

   b.setdata(20);  

   min(a,b);  

    return 0;  

 }  

 

Output:

 

10

In the above example, min() function is friendly to two classes, i.e., the min() function can access the private members of both classes A and B.

To Wind Up:

 

The friend function in C++ serves as a powerful tool for breaking the encapsulation barrier, allowing non-member functions special access to private and protected members of a class. Its flexibility enables intricate relationships between classes, enhancing the versatility of C++ programming. As you explore the world of software development further, contemplate broadening your skill set through an Advanced Certification Program in Data Science & Analytics. Arm yourself with the essential skills and knowledge required to thrive in this ever-evolving domain, opening doors to a fulfilling career in data-driven innovation. Seize the opportunity to advance your proficiency in data science and analytics today!

 

 

FAQs
A friend function, although not a member of a class, can access the private and protected members of that class. These functions are not regarded as class members; rather, they are regular external functions granted special access privileges.
In C++, "friend" indicates that a non-member function can access the private members of the class. On the other hand, "inline" signifies that there is no actual function call; instead, the body of the function is duplicated at every call site, typically in assembly code.
Friend function in C++ is the creative function that breaks the data hiding in an object-oriented programming language. The data hiding prevents the access of private members externally from the class. The protected members are inaccessible from the outside and can only be accessed by the derived classes.
In C++, a friend function serves as a versatile tool that circumvents the data hiding inherent in object-oriented programming languages. Data hiding typically bars external access to private members of a class. Similarly, protected members remain inaccessible from outside the class and can solely be accessed by derived classes.
Since it's not within the scope of the class, it can't be called using the object. Instead, it's invoked just like a regular function without needing an object. Direct access to member names isn't possible; it requires using the object name followed by the dot membership operator and the member name.

Book a free counselling session

India_flag

Get a personalized career roadmap

Get tailored program recommendations

Explore industry trends and job opportunities

left dot patternright dot pattern

Programs tailored for your Success

Popular

Data Science

Technology

Finance

Management

Future Tech

Upskill with expert articles
View all
Hero Vired logo
Hero Vired is a leading LearnTech company dedicated to offering cutting-edge programs in collaboration with top-tier global institutions. As part of the esteemed Hero Group, we are committed to revolutionizing the skill development landscape in India. Our programs, delivered by industry experts, are designed to empower professionals and students with the skills they need to thrive in today’s competitive job market.

Data Science

Accelerator Program in Business Analytics & Data Science

Integrated Program in Data Science, AI and ML

Accelerator Program in AI and Machine Learning

Advanced Certification Program in Data Science & Analytics

Technology

Certificate Program in Full Stack Development with Specialization for Web and Mobile

Certificate Program in DevOps and Cloud Engineering

Certificate Program in Application Development

Certificate Program in Cybersecurity Essentials & Risk Assessment

Finance

Integrated Program in Finance and Financial Technologies

Certificate Program in Financial Analysis, Valuation and Risk Management

Management

Certificate Program in Strategic Management and Business Essentials

Executive Program in Product Management

Certificate Program in Product Management

Certificate Program in Technology-enabled Sales

Future Tech

Certificate Program in Gaming & Esports

Certificate Program in Extended Reality (VR+AR)

Professional Diploma in UX Design

Blogs
Reviews
Events
In the News
About Us
Contact us
Learning Hub
18003093939     ·     hello@herovired.com     ·    Whatsapp
Privacy policy and Terms of use

© 2024 Hero Vired. All rights reserved