Friend Function in C++ with Example
A friend function is a function that is not a member of a class but has access to the class's
private and protected members. However, a situation can be created where two classes could share a common function. For instance, assume two classes called Engineer and Postmaster. Here we have to use the function called salary to operate on the objects of both these classes.
Friend functions are not considered class members and they are normal external functions that are given special access privileges. Friends are not in the
class's scope. They are not called using member-selection operators
(. and ->) unless they are members of another class.
A friend function is declared by the class that is granting access. They
friend function declaration can be placed anywhere in the class declaration.
Some of the special characteristics of a friend function are
- − A friend function is a function that has full access to the private members of a class but not itself a member of that class.
- −A friend function can be defined anywhere in the C++ program and not necessarily immediately after the class definition.
- − The friend function doesn't have this pointer.
- − A function can be friend of more than one class
- − The friend function accepts objects as arguments.
Simple Program for Friend Function Using C++ Programming
The value of a is :44
Explanation of the program
The msg() function is a friend function to the class Friend_Function. It has been declared inside the
Friend_Function class. It accepts arguments here only objects i.e. s1. It does access the private data member of sample class. Only a friend function can do so.
© 2016-2019, Codeverb.com - All Rights Reserved