Friend Function in C++ | Features, Types, & More
According to a study, 73% of C++ developers regularly utilize friend functions in their code. Friend functions offer a clear, prudent way to keep classes encapsulated while still enabling controlled external access when needed. They represent a core principle of object-oriented programming.
Let’s understand what is a friend class in C++, defining and using friend functions in your C++ programs. Understand the basics of the friend function in C++, discuss typical use cases, and provide examples to demonstrate the power and flexibility of this key C++ feature.
What is a Friend Function?
In C++, a friend function is a specific kind of function that has access to a class’s private and protected members. Unlike typical class members, the friend function in C++ is declared within the class but is not considered a member of the class. Consider a class to be a collection of related variables and functions. By default, these variables and functions have varying levels of accessibility, with private members-only accessible within the class. A friend function, on the other hand, works as a trusted ally who can bypass these access limitations and interact with private users.
Characteristics of Friend Functions
Friend functions in C++ provide access to private and protected class members from outside that class.
- They allow the friend function to access the internals of the class directly.
- Friend functions expose some functionality of a class to external code in a controlled manner.
- It provides selective access to internal details we deem appropriate to share with other program parts. This enables flexibility and reusability while hiding implementation details meant to be encapsulated.
- Friend functions in C++ are declared inside the class using the friend keyword. This marks them as “friends” of the class, allowing them to bypass the usual access restrictions.
- They can freely access private and protected members as if they were public. For example, if we have a class representing rational numbers, we might make a friend function to perform the simplification of fractions. It would need to access the private numerator and denominator members.
- Friend functions result in code that is easier to maintain as changes are confined and intentional. The boundaries of unintrusiveness remain clearly defined. One must learn C++ in depth as, apart from OOPs, friend functions promote a clean, robust design with minimal unintended side effects.
The syntax of the friend function in C++ is
class className {
---- ------ ------
friend returnType functionName(arguments);
---- ------ ------
}
How to Declare and Define a friend function in C++
In C++, a friend function is declared inside a class and defined outside of it. It has access to secret and protected members of the class, which encourages encapsulation.
Here’s how we declare and define the friend function:
Declaring Friend Function
We use the friend keyword in the class declaration to declare a friend function. For example
class Test
{
friend void display(Test); // friend function declaration
};
Here, we have declared the display() function as a friend function to the Test class. This means that display() can access private and protected members of the Test class.
Defining a Friend Function in C++
We define a friend function outside the class as a normal function. For example
void display(Test t)
{
// can access private members of the Test
}
Since display() is a friend function of Test, it can access private members of the Testclass.
Why Use Friend Functions?
Here are the reasons to use friend functions:
- To utilize non-member functions that need access to class members – Sometimes, we have a function that logically works on a class but does not technically belong to that class. We can declare such functions as friends.
- To optimize resource usage – Sometimes, to optimize CPU and memory usage, we declare a function outside a class to avoid the overhead of a ‘this’ pointer and make it a friend to grant it access to private members.
- For operators overloading – We often overload operators as friend functions because, logically, they act on a class but do not belong to it.
What is a Friend Class in C++
Friend classes in C++ allow for a close relationship between two classes by permitting access to private and protected members, which is usually not allowed. This is declared using the ‘friend’ keyword. For instance:
class Test; // Forward declaration
class Friend { ... };
class Test {
friend Friend; // Friend class declaration
...
};
Here, the ‘Friend’ class is a companion of ‘Test’ and can access its private members.
Features of Friend Classes in C++
Friend classes enable a flexible and potent feature of C++ that ought to be utilized prudently. When appropriately employed, they can augment efficiency and streamline program resource utilization. Some salient features regarding friend classes are listed below:
- A C++ friend class can access private and protected members of the befriended class, analogous to a friend function.
- Friendship is not transitive. A friend of a friend is not a friend. Only the specific classes declared as friends have special access.
- Friends should be used sparingly since they diminish encapsulation. They should only be declared when necessary to implement a closely cooperating class.
- Excessive use of friends can result in disorganized code that is difficult to comprehend and maintain.
- Friendship is not inherited. A derived class is not a friend of its base class’s friends. Friendship needs to be explicitly specified in all cases.
- An entire class is either a friend or not a friend. We cannot declare specific members of a class as friends.
- Friend classes are often used when two classes cooperate closely, and access to private members improves efficiency. For example, iterators and containers are usually made friends.
- If a class uses a significant amount of resources (memory/CPU), making a friend class can optimize usage since no encapsulation is required between friends.
- Even though friend classes can access private members, they do not become part of the class interface. The class can still change its private members freely without affecting friend classes.
Why Use Friend Classes?
Friend classes are useful when:
- Two classes are closely related and cooperate a lot: For example, iterators and containers. Making them friends avoids excessive use of accessor functions.
- When a class uses a significant amount of resources (memory/CPU), making a friend class can optimize the usage since no encapsulation is required between friends.
Types of Friend Functions
There are two kinds of friend functions
Non-Member Friend Functions
These functions are declared in the class definition but are not class members. They have access to the private and protected members of the class. These functions are often used to provide external functions. These external functions operate on the private data of a class.
Member Friend Functions
Member Friend Functions are declared as members of a class and friend functions in another class. They are declared as the private and protected members of the class they are friends with. They can access the private and protected members of the class. They are often used to provide privileged access to the private data of a related class.
Conclusion
Friend functions and Friend classes allow flexible and selective access to class members while maintaining encapsulation and interface stability. They represent a powerful feature of C++ that you should utilize in your programs.