C++ Friend Class
A controlled exception to the encapsulation principle is provided by the friend class concept in C++, which allows one class to allow its private protected members to access another class. This feature preserves data integrity while promoting design flexibility.
A class can directly access a privately protected member as if it were its own when the friend keyword is being used to identify another class as a friend. The friend class is able to change its private members because this method is available to all instances of the declarer class.
The friend class declaration is usually found outside the class access field (public, private, and safe) in the class description. Example:
Class MyClass {
Private:
int privateMembership;
Public:
// FriendClass is declared a friend of MyClass
A group of friends is a group of friends;
};
The friend class here, FriendClass, gets access to the private members of MyClass. However, it is important to realize that friendship is not for everyone. Just because a class is a friend of another does not automatically give them access to their private members. It is a one-sided relationship established by the reporting team.
Friendship allows for specific situations where tight communication or shared functionality between classes is required without reference to the broader functionality. It is often used in situations such as the use of special algorithm functions that require direct access to individual members of the class or when using operator overload where individual members need access.
However, excessive use of friend classes can break encapsulation, which can make the code unmaintainable or unreasonable. Friendship classes should be used sparingly, and attempts should be made to retain the benefits of encapsulation wherever possible.
Specifically, the concept of friend classes in C++ provides a targeted way to allow external classes to access privately protected members of a class. Enforcing controlled communication encourages and simplifies specific programming without completely compromising data storage and encapsulation principles
Syntax:
friend class class_name; // base class declaration
Examples:
// C++ Program to demonstrate the
// functioning of a friend class
#include <iostream>
using namespace std;
class JT {
private:
int private_variable;
Protected:
int protected_variable;
Public:
JT()
{
private_variable = 15;
protected_variable = 69;
}
// declaration OF FRIEND CLASS
friend class Fd;
};
// Here, class Fd is declared as a
// friend inside class JT. Therefore,
// Fd is a friend of class JT. Class Fd
// can access the private members of
// class JT.
class Fd {
public:
void display(JT & p)
{
cout << "The value of Private Variable = "
<< p.private_variable << endl;
cout << "The value of Protected Variable = "
<< p.protected_variable;
}
};
// Driver code
int main()
{
JT j;
Fd frnd;
fri.display(j);
return 0;
}
Output:
The value of Private Variable = 15
The value of Protected Variable = 69
Friend Function:
In C++, a friend function can have exclusive access to secret and protected members of a class, just like a friend class. Since they have been declared friends, these non-member functions have access to and control over the class's private and protected members.
A friend's function could be:
- A global function
- A function that is a member of another class
Global function:
Global functions can be called friend functions within a class. This allows those global functions to access members of a class that are as private or protected as members of that class.
Syntax:
friend return_type function_name (arguments); // for a global function
The role of a global role as a friend role is particularly useful in situations where you have a role that needs access to the private content of a class but is not part of that class's interface or process, e.g., Not a member of the class, to change directly to private members In cases like this, you can declare that event as a friend in the class:
Code:
Private:
int privateMember;
Public:
MyClass() : privateMember(0) {}.
friend void globalFunction(myClass & obj); // Declare global job as friend
};
void globalWork(myClass& obj) {
obj.privateMembers = 6; // Accessing privateMember as a friend function
}
int main() { .
myClass obj;
globalWork ( obj ); // Call the global function
return 0 ;
}
In this case, global Function is a global function that MyClass has identified as a friend. It can work like a member function, accessing and modifying the MyClass private member privateMember directly.
Friend Function as a Member of a Different Class
In C++, a member function of a different class can also be declared as a friend function. In C++, you can use a member function of another class as a friend function by using the example below:
Code:
// C++ program to create a member function of another class
// as a friend function
#include <iostream>
using namespace std;
class base; // forward definition needed
// another class in which function is declared
class anotherClass {
Public:
void memberFunction(base& obj);
};
// base class for which friend is declared
class base {
private:
int private_variable;
Protected:
int protected_variable;
Public:
base()
{
private_variable = 12;
protected_variable = 69;
}
// friend function declaration
friend void anotherClass::memberFunction(base&);
};
// friend function definition
void anotherClass::memberFunction(base& obj)
{
cout << "Private Variable: " << obj.private_variable
<< endl;
cout << "Protected Variable: " << obj.protected_variable;
}
// driver code
int main()
{
base object1;
anotherClass object2;
object2.memberFunction(object1);\
return 0;
}
Output:
The value of Private Variable = 12
The value of Protected Variable = 69
Friend Function Features
- In C++, a buddy function is a unique function that has access to a class's private and protected data even though it isn't a member function of the class.
- A friend function is an ordinary or non-member function of a class that is designated as such within the class by using the term "friend." A function can be granted all access permissions by defining it as a friend.
- The friend function's function declaration is the only place the keyword "friend" appears; neither the function definition nor the function call contains it.
- Similar to an ordinary function, a friend function is called. The dot operator and the object name cannot be used to invoke it.
- It could take the object as an input whose value it wishes to retrieve.
- Any class section, whether public, private, or protected, may declare a friend function.
Although the friend function gives us access to private information, it is not without its drawbacks. The list of benefits and drawbacks of C++ friend functions is as follows:
Benefits of Friend Functions:
- A friend function can access members without requiring it to inherit the class.
- By gaining access to two classes' private data, the friend function serves as a mediator between them.
- It can be applied to make overworked operators more versatile.
- It may be announced in the class's protected, private, or public areas.
The drawbacks of friend functions:
- The law of data hiding is broken by friend functions, which allow access to private members of a class from outside the class.
- Friend functions are not allowed to perform any run-time member polymorphism.
- Crucial Information Regarding Friend Functions and Classes
- Friends should only be utilized in certain situations. In object-oriented programming, the value of encapsulating distinct classes is diminished when an excessive number of functions or external classes are declared as friends of a class with access to protected or private data.
- Mutual friendship does not exist. Even if class A is B's friend, this does not mean that B automatically becomes friends with A. It is not inherited to be friends.
A function that is accommodating to various classes
// C++ Program to demonstrate
//How friend functions work as
// a bridge between the classes
#include <iostream>
using namespace std;
// Forward declaration
class PQR;
class ABC {
int p;
Public:
void set_data(int x)
{
p = x;
}
friend void max( ABC, PQR);
};
class PQR{
int q;
Public:
void set_data(int x)
{
q = x;
}
friend void max(ABC, PQR);
};
void max(PQR z1, ABC z2)
{
if (z1.p > z2.q)
cout << z1.p;
else
cout << z2.q;
}
// Driver code
int main()
{
PQR_pqr;
ABC_abc;
_pqr.set_data(15);
_abc.set_data(20);
// calling friend function
max(_pqr, _abc);
return 0;
}
Output:
20
Conclusion
In conclusion, friend functions and classes in C++ provide a mechanism to allow all external functions or classes access to the protected privacy of the class. This approach violates the usual restrictions of encapsulation and provides externality-identified services that are able to apply directly to otherwise inaccessible members.