Sumona

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 3

Experiment Number: 06

Experiment Name: Introduction to Friend Function with Implement Code.

Objectives:
1. Ensure restricted access to private and protected members of a class while upholding
encapsulation principles.
2. Facilitate non-member functions to access class internals, thereby enhancing
implementation flexibility and extensibility.
3. Optimize access to class internals to enhance performance when necessary, promoting
efficiency in program execution.
4. Minimize redundant member functions within a class to foster cleaner and more
maintainable designs, reducing complexity and enhancing readability.
5. Implement intuitive code for user-defined types by leveraging non-member friend
functions, enhancing usability and clarity in code implementation.

Introduction: Like a friend class, a friend function can be granted special access to private
and protected members of a class in C++. They are the non-member functions that can access
and manipulate the private and protected members of the class for they are declared as
friends.

A friend function can be:

 A global function
 A member function of another class.
Implement Code:
Output:

Conclusion:
Friend functions in C++ are a useful tool for accessing private or protected members of a
class from outside the class scope. They promote flexibility in designing classes and help in
achieving encapsulation while still allowing specific functions or classes access to private
data. By declaring a function as a friend of a class, it gains special privileges to access private
members without violating encapsulation principles. This feature enhances the versatility and
efficiency of C++ programming, making it easier to implement complex systems with well-
defined boundaries between different components. Overall, friend functions provide a
valuable mechanism for managing data accessibility and improving code organization in C++
programs.

You might also like