A friend function of class is defined outside that class's scope, yet has the right to access the non-public (and public) members of the class. Even though the prototype for friend function appear in the class definition, friends are not members functions.
Using friend functions can enhance performance. A friend can be a function,
function template, or member function, or a class or class template, in which
case the entire class and all of its members are friends.
Reference: C Plus Plus How to Program 8th Edition by Paul Deitel
To declare a function as friend of a class, precede the function prototype
in the class definition with keyword friend as below:
class student {
private:
int ST_Id;
string ST_Name;
public
friend void DisplayName(student ST); //_prototype friend function
void setName(string Name);
}
To declare all member function of a class as friend with other class,
place a following declaration in the definition of class:
friend class ClassName;
Example: we have ClassA
and
ClassB
and we want all member functions of
ClassB
as friends of ClassA
, declaration as
below definition of class ClassA
:
friend class ClassB;
Reference: C Plus Plus How to Program 8th Edition by Paul Deitel
0 Comments