Friend Function in c plus plus with Use Cases

The use of friend functions in C++ allows the non-member functions to access the private members of a class and the protected members as well which is rather convenient in particular cases of programming.

Friend Function in c plus plus with Use Cases

Friend Function in c plus plus with Use Cases

What is the Friend Function in C++?

A nonmember friend function in the C++ programming language is a nonmember function that has special rights to access both the private and the protected data of a given class. Such functions are defined as friends in the body of the class and at any of the sections (private, protected, or public), much the same as it does not influence its functionality. The friend keyword is used in declaration of the function, but not in the definition or call of the function.

Friend Functions Characteristics

Not a Member Function A friend function is not a class member of the class it is befriended in, so it does not see this pointer and cannot be directly called on the object.

Access to Private and Protected Members: A non-member friend function can see all the private and protected members and functions of the class it is declared a friend of, nonetheless.

Being stated in the Class: A friend-function declaration must form part of the body of the class it is befriending.

The friend function is defined as an externality: The friend function definition is out of the class scope and it is treated as an ordinary non-member function.

Friendship Not Mutual: Should Class A declare Function F a friend, then Function F can inspect the private members of Class A, but the converse is not automatic: Class A will not necessarily have access to Function Fs (had Function F been a class).

Friendship Not Inherited: Friendship is not inherited and in case a base class has a friend function that function does not automatically make itself a friend to derived classes.

Friend Functions Rules

a friend might be either a global or a member of another class.

  • In declaring a global function a friend, it is only on the declaration of the function as a friend within the class.
  • To make a member function of one class a friend of a second, a forward declaration of the second class, before the befriending class definition, is mandatory in case the effect is to be given to each of the classes after declaration as far as the friend member function is concerned.
  • When a member of a class is made a friend of the other, care is necessary that both classes are defined prior to the defining of the friend function; the order of definition of classes is significant in this event.

 

C++ C++ C++ Friend Practical Examples Function

Friend functions are especially practical when a function is required to work with the personal information of several classes or operator overloading to external functions is wanted.

1 Operator Overloading

Use in operator overloading, especially of input/output stream operators (<< and >>) and binary arithmetic operators is one of the most canonical uses of friend functions. As an example, implementing overloading of the << operator to print object information, the coding must frequently perform operations on the internal members of the class, and defining it as a non-member friend function will permit the syntax std::cout << object; to be naturally interpreted.

Let us look at a Point class that has privately defined x and y coordinates. In order to print `Point` instances via `std::cout` one would generally define `operator<<` as a friend:

This enables the operator<< to access p.x and p.y though operator<< is not a member of the Point type.

2. Multiple-Class Friendly Functions (Bridge Functions)

There are cases when one function must work with the personal information of two or more of various classes. In this kind of situation a friend method can serve as this type of middle ground between these classes and provide it with the required access to all the involved classes' private and protected members.

3. Information with Narrowly coupled Classes

Where several classes collaborate to model a single logical object, friend functions or classes may be used to deal with shared private state and invariants in complex data structures.

4. Debugging and Testing

White-box testing allows testing with Friend functions: In this case a test function must visit or change the internal private state of a class in order to achieve complete testing. It enables appropriate encapsulation of the core application code with some acceptable entry points to be used during testing.

5. Selective Access Control

Whereas a public member function can be accessed in any manner and a member function will not be accessible at all, friend functions give a "white list" to certain functions or classes to evade normal access controls. This makes it possible to do fine-grained declarations as to which non-member entities should be allowed to access internals of a class.

6. Serialization

Friend functions can have applications in serialization in that classes can easily (and yet not compromise encapsulation) deal with serialization and deserialization to their privately contained information.

Best Practices in the usage of Friend Functions

Although powerful, since the friend functions allow one to violate the principles of object oriented programs especially the encapsulation and data hiding features, one should use the friend functions sparingly.

In Cool Places with Purpose In Mind: Friend actions should be used in only those cases where they provide a specific useful purpose in design or implementation that cannot safely, satisfactorily and elegantly be realised using only public interfaces. There is a threat of tight coupling and loss of maintainability which may arise due to over use.

When an Option, Use Member Functions: In cases where it is possible to access a task through public member functions, they are to be used as opposed to the use of friend functions.

Type Safety: The use of friend functions does not disable type safety of your program.

Document Usage: When a friend is employed to implement a function or a class document the reasons why it was done and indicate the particular member of the class that it must use and why this was done.

Avoid Over- Privilege: Provide friendship to only those functions or classes which really need access to the private/protected members. Do not make an entire record a friend just because a particular member operation of the record has to access the access.

Think of alternatives: Instead of using friend functions, consider using other design patterns or techniques, e.g. to allow controlled access to some needed data, one may use public getter/setter methods, although these may occasionally cause more verbose code. It is however vital to realise that the simple addition of public getters setters cannot always be said to be more encapsulated than passive since they can potentially allow arbitrary access to internal state.

Uncodemy Courses C++ and Friend Functions

To the individuals who want to further explore the concepts of C++ programming such as the friend functions, Uncodemy provides training programs that suit them. Uncodemy is one of the popular training institutes of IT that offers their classes in the field of Data Science, Full Stack Development, Python, Java, Software Testing, Data Analytics, and Digital Marketing.

The given documents do not give a particular description of such courses as devoted to the study of the so-called Friend Functions, however, such general courses on C++ programming usually involve complex topics of this type. Uncodemy provides, as an example:

° C Programming live project based courses: These are the courses that have been designed by high graded mentors and which are appropriate in regard to acquiring experience. The kind of course taught under such foundations would most probably have object oriented programming concepts and classes and their advanced forms such as friend functions.

° Full Stack Development Training Course: This course is a broader course so chances are high that this course entails C++ in its curriculum since C++ has been used in systems programming and in other application areas where performance constitutes a major concern.

° Online Courses: Uncodemy specializes in the provision of best courses in Delhi and to this end, some of their courses, including the Executive PG Certification in AI Powered Full Stack Development by upGrad along with IIIT Bangalore, are online.

If one is interested in particular modules or more specific knowledge about friend functions in the Uncodemy C++ curriculum, the official Uncodemy site is to be visited or one can contact their admissions department. The best way to find out what exactly they cover in regard to any particular feature of C++ is to check their All Courses page or the description of the course.

Conclusion

The concept of friend functions in C++ is a strong checking tool to permit external functions or classes to access internal tools, particularly you cannot do that with protection and encapsulation. Although it appears to be a vulnerability in the OOP postulates, their judicious application in a case of operator overloading, inter-class messages and special data structures may give rise to cleaner and more efficient programs. But it is important that they should be used in a sensible manner keeping in mind the clarity of design, careful documentation and following the best practices to ensure code readability and avoid any unwanted side effects. Learning more, such as on Uncodemy, can also help a programmer reinforce his understanding of such complex aspects of C++.

Placed Students

Our Clients

Partners

...

Uncodemy Learning Platform

Uncodemy Free Premium Features

Popular Courses