In C++, there are situations when we want to allow a non-member function or a non-member class to access the private and protected members of a class. This can be achieved by using the concept of friend functions and friend classes.This feature enhances flexibility in designing class hierarchies and facilitates communication between classes. This tutorial explores the concepts, syntax, and use cases of friend functions and friend classes in C++.
Friend Function
A friend function of a class is a function that is not a member of the class but has access to the private and protected members of the class. A friend function can be declared inside the class using the keyword "friend". The friend function can be a normal function or a member function of another class.
The syntax for declaring a friend function is as follows:
class className { private: // private members protected: // protected members public: // public members friend returnType functionName(arguments); };
A friend function can be defined outside the class or inside the class. If the friend function is defined inside the class, it must be preceded by the keyword "friend".
The friend function can be called just like a normal function, and it can access the private and protected members of the class.
Here is a sample C++ program to demonstrate the use of a friend function in C++.
#include <iostream> using namespace std; class Rectangle { private: int width; int height; public: Rectangle(int w = 0, int h = 0) : width(w), height(h) {} // Friend function friend int area(Rectangle &); }; // Friend function definition int area(Rectangle &rect) { return rect.width * rect.height; } int main() { Rectangle rect(5, 7); cout << "Area of rectangle: " << area(rect) << endl; return 0; }Output
Area of rectangle: 35
In this example, the area function is a friend function of the Rectangle class, and it has access to the private and protected members of the class.
Friend Class
A friend class is a class that has access to the private and protected members of another class. A friend class can be declared inside a class using the keyword "friend". The syntax for declaring a friend class is as follows:
class className1 { private: // private members protected: // protected members public: // public members friend class className2; };
In this example, the className2 is a friend class of the className1. The friend class can access the private and protected members of the className1.
Here is a sample C++ program to demonstrate the use of friend classes in C++.
#include <iostream> using namespace std; class Rectangle; class Square { private: int side; public: Square(int s) : side(s) {} friend class Rectangle; }; class Rectangle { private: int length; int breadth; public: Rectangle(int l, int b) : length(l), breadth(b) {} Rectangle(Square &s) { length = s.side; breadth = s.side; } int area() { return length * breadth; } }; int main() { Square square(10); Rectangle rectangle(square); cout << "Area of rectangle: " << rectangle.area() << endl; return 0; }Output
Area of rectangle: 100
In this example, we have created two classes Square and Rectangle. Square class has a private variable side, and a friend class Rectangle. The Rectangle class has a private variable length and breadth. The Rectangle class has a constructor which takes an object of Square class as an argument and initializes the length and breadth with the side of the square.
The main function creates an object of Square class and passes it to the constructor of Rectangle class. The area function of the Rectangle class is used to calculate the area of the rectangle. The friend class relationship between Square and Rectangle allows the Rectangle class to access the private variables of the Square class.
Friend Function vs Friend Class
- Friend Function
- A friend function is a non-member function that is granted access to the private and protected members of a class.
- It is declared using the friend keyword in the class declaration.
- Friend functions are useful when external functions need to access the private members of a class, providing a way to extend functionality without making those members public.
- Friend Class
- A friend class is a non-member class that is granted access to the private and protected members of another class.
- It is declared using the friend keyword in the class declaration.
- Friend classes are beneficial when there is a need for close collaboration between classes, allowing one class to access the private members of another.
- Choosing Between Friend Function and Friend Class
- Choose a friend function when the functionality can be achieved with a standalone function that does not need to maintain any state.
- Choose a friend class when there is a need for more extensive collaboration between classes, and the functionality is better encapsulated within a separate class.
Rules and Best Practices for Friend Functions and Classes
- Granularity : Grant friendship at the appropriate level of granularity. Avoid making entire classes friends if only specific functions or members need access.
- Encapsulation : Use friend functions and classes judiciously to preserve encapsulation. Minimize the exposure of private members and only grant access when necessary for collaboration.
- Minimize Dependencies : Limit the use of friend functions and classes to minimize dependencies between classes. Excessive use can lead to a tightly coupled design, reducing code modularity.
- Document Design Decisions : When using friend functions or classes, document the design decisions clearly. Explain the reasons for granting friendship and how it enhances the overall design.
- Prefer Member Functions : Whenever possible, prefer member functions over friend functions or classes. Member functions are more closely associated with the class and provide a more object-oriented design.
Conclusion
Friend functions and friend classes in C++ provide a means to extend collaboration between classes by allowing external functions or classes access to private and protected members. When used judiciously, these features enhance flexibility in class design without sacrificing encapsulation.
Understanding the syntax, use cases, and best practices associated with friend functions and classes is crucial for designing maintainable and modular C++ code. By carefully considering the needs of collaboration and encapsulation, developers can create robust class hierarchies that strike a balance between flexibility and security.
As you incorporate friend functions and classes into your projects, keep in mind the principles discussed in this tutorial. With a clear understanding of when and how to use these features, you can leverage the power of C++ to build scalable and well-organized software systems.