1. Home
C++ Tutorial

Explore C++ Tutorials: Exploring the World of C++ Programming

Discover comprehensive C++ tutorials designed for beginners and advanced programmers alike. Enhance your coding skills with step-by-step guides and practical examples.

  • 77 Lessons
  • 15 Hours
right-top-arrow
24

Friend Class in C++: Understanding Friend Functions and Usage

Updated on 25/09/2024421 Views

During my time learning and working with programming, I have come across a subtle but strong feature known as friend classes and functions in C++. This part of the language lets some special external functions or classes get to the private and protected parts inside other classes.

Throughout this tutorial, I will delve into what friend class in C++ and c++ friend function are, how they work, and when to use them, all while integrating essential keywords to enhance our understanding.

What is a Friend Class in C++?

As I understand, a friend class in C++ is one that has permission to reach the private and protected parts of another class. This connection allows for bypassing encapsulation but in a managed way. Although it may seem to be against the principle of encapsulation, this concept is in fact a strong technique that provides great benefits if applied with care.

How is a Friend Class Declared?

Declaring a cpp friend class in C++ is straightforward. Inside the class whose members you want to access, you use the friend keyword followed by the class name. Here’s how I typically declare a friend class in C++:

class MyClass {

friend class FriendClass; // FriendClass can now access private and protected members of MyClass

private:

int data;

};

In this code, FriendClass is a friend of MyClass and can access its private and protected members, demonstrating a classic c++ friend class example.

What are the Advantages of Using Friend Classes?

From my experience, the advantages of using cpp friend class in C++ include:

  1. Enhanced collaboration between classes: Friend classes allow for two or more classes to work closely together, sharing data and functionality without exposing sensitive information to the rest of the program.
  2. Controlled access: Unlike public members, friend class in C++ provides access to only the classes explicitly specified, which maintains a higher level of control compared to fully public data.

What are the Drawbacks of Friend Classes?

While friend classes are useful, they do come with some drawbacks:

  1. Encapsulation breakdown: Using friend class in C++ breaks down the encapsulation to a certain extent, which can make the code harder to understand and maintain.
  2. Tight coupling: cpp friend class creates tight coupling between classes, which can lead to issues if the software needs to be changed or scaled later.

Can Friend Classes Access Private and Protected Members of Other Classes?

Yes, friend class in C++ can access private and protected members of the class that declares them as friends. This is the primary feature that distinguishes cpp friend class from regular classes, which cannot access private or protected members of other classes.

When Should I Use Friend Classes?

I use friend class in C++ when I need to allow very close interaction between two or more classes, but I don’t want to expose certain details to the entire program. Here are a few scenarios where cpp friend class are particularly useful:

  • Operator overloading: When you overload operators, if you use friend function in c++, it helps to make the code look neater and easier to understand.
  • Internal helper classes: For complicated data structures, it is sometimes needed for support classes to reach the inside parts of the main class without showing these specifics to everyone.

Can a Friendship be Inherited in C++?

No, in C++, friendships do not pass down. When a base class is the friend of another class, this friendship does not extend to classes that come from it. Every subclass must state its own friendship explicitly if it requires. This method confirms that choosing to be friends is intentional in the design, preventing unintentional breaks in encapsulation.

What is the Difference Between Friend Class and CPP Friend Function in C++?

The main difference between a friend class in C++ and a c++ friend function is the scope of access:

  • Friend class in C++: A friend class in C++ can access private and protected members of another class across all its methods, while a C++ friend function is allowed this access for just one specific function.
  • C++ friend function: A C++ friend function is a separate function, not belonging to any class, which is given permission to use the private and protected parts of the class where it's declared as a friend.

To better grasp the distinctions between a friend class and a friend function in C++, consider this explanation:

Aspect

Friend Class in C++

C++ Friend Function

Definition

A class that is given the ability to access the private and protected members of another class.

A standalone function (not a member of any class) given access to the private and protected members of a class.

Scope of Access

Can access all private and protected members of the class in which it is declared a friend.

Can access specific private and protected members of the class in which it is declared a friend.

Declaration

Declared inside the class whose members it needs to access using the friend keyword followed by the class name.

Declared inside the class whose members it needs to access using the friend keyword followed by the function prototype.

Access to Multiple Classes

A single friend class in C++ can be a friend to multiple classes.

A single c++ friend function can be a friend to multiple classes, but needs separate declarations.

Granularity of Access Control

Access is broad; once declared, all members of the friend class can access the target class's members.

Access is more granular; only the friend function itself gains access, not all functions of a class.

Usage in Overloading

Not typically used in operator overloading.

Commonly used in operator overloading to allow non-member functions to access private data for operations.

Encapsulation

Breaks encapsulation more broadly by allowing another class extensive access.

Breaks encapsulation in a more limited manner, providing access only to the required function.

Inheritance

Friendship is not inherited. If a base class is a friend, the derived class is not automatically a friend.

Friendship is not inherited; similar rules apply as with friend classes.

Ease of Maintenance

Can lead to tighter coupling between classes, potentially making maintenance harder.

Typically leads to less coupling compared to friend classes, making maintenance easier.

Example Declaration

friend class FriendClassName; within the class declaration.

friend ReturnType FriendFunctionName(Parameters); within the class declaration.

Let’s also look at an example to illustrate this difference. Here’s a friend function program in C++:

Example:

Code:

#include <iostream>

using namespace std;

class Box {

private:

int width;

public:

Box() { width = 0; }

friend class BoxPrinter; // Friend Class

friend void printWidth(Box& b); // Friend Function

};

// Friend Class

class BoxPrinter {

public:

void print(Box& b) {

cout << "Width of box: " << b.width << endl;

}

};

// C++ Friend Function Example

void printWidth(Box& b) {

cout << "Width of box: " << b.width << endl;

}

int main() {

Box box;

BoxPrinter printer;

printer.print(box);

printWidth(box);

return 0;

}

Output:

Width of Box: 0

Width of Box: 0

In this code, both BoxPrinter (a cpp friend class) and printWidth (a c++ friend function) can access the private member width of Box.

Concluding Remarks

Grasping the concept of friend class in C++ and learning about the c++ friend function has greatly enhanced my skills for crafting code that is tidy, performs well, and delivers results. These elements contribute to keeping a good level of encapsulation while also permitting access to certain inner parts of a class when needed, something very beneficial especially within intricate systems or extensive libraries.

If you want to learn more about C++ or different computer languages, I suggest you check out the software engineering programs on UpGrad. They have a good setup that helps you get a strong base and improve your abilities and dive into good nuances of different programming techniques.

Keep in mind, the friend keyword is powerful but use it with care for code that is easy to manage and safe. Enjoy coding!

FAQs on Friend Classes and Friend Functions

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

In C++, a friend class is one that has special permission to reach into another class's private and protected parts.

2. How is a friend class declared?

In C++, to declare a friend class, one uses the keyword 'friend' within the definition of the class whose member elements it wishes to reach.

3. What are the advantages of using friend classes?

Benefits are easier teamwork among different groups, managing who can see important information carefully, and adding new features without breaking the rules of keeping things separate.

4. What are the drawbacks of friend classes?

The disadvantages could be breaking into the containment, a stronger connection among classes and it may get more complicated to look after the code.

5. Can friend classes access private and protected members of other classes?

Yes, a friend class in C++ has the ability to reach private and protected parts within the class that has named it as a friend.

6. When should I use friend classes?

In C++, I apply the concept of friend class for ensuring close interaction between classes, which helps in creating specific functions without having to expose private members more than needed.

7. Can a friendship be inherited in C++?

In C++, the friendships are not passed down. When a base class is friends with something, this relationship does not extend to any class that comes from it.

8. What is the difference between friend class and friend function in C++?

In C++, a friend class is one that can reach the private and protected parts of another class. Also, a C++ friend function is allowed to access the private and protected elements inside the class where it has been declared.

Rohan Vats

Rohan Vats

Software Engineering Manager @ upGrad. Passionate about building large scale web apps with delightful experiences. In pursuit of transforming eng…Read More

Need Guidance? We're Here to Help!
form image
+91
*
By clicking, I accept theT&Cand
Privacy Policy
image
Join 10M+ Learners & Transform Your Career
Learn on a personalised AI-powered platform that offers best-in-class content, live sessions & mentorship from leading industry experts.
right-top-arrowleft-top-arrow

upGrad Learner Support

Talk to our experts. We’re available 24/7.

text

Indian Nationals

1800 210 2020

text

Foreign Nationals

+918045604032

Disclaimer

upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...