You are on page 1of 15

Friend Function

• Outline:
• Standalone Friend Function
• Friend Class
Friends of Classes
• Friend: a function or class that is not a member
of a class, but has access to private or protected
members of the class
• A friend function can be a stand-alone function
or a member function of another class
• It is declared a friend of a class with friend
keyword in the function prototype
friend Function Declarations

• Stand-alone function:
friend void setAVal(intVal&, int);
// declares setAVal function to be
// a friend of this class
Friend Function
Friend Function

• The declaration of friend function can be placed anywhere in the


class i.e. public or private.
Finding Distacne Squre without
Friend Function
Finding Distacne Squre without
Friend Function

• More approriate way to find square of distance is to use the following


notation.
Finding Distacne Squre with
Friend Function
Finding Distacne Squre without
Friend Function
friend function
friend Class Declarations
• Class as a friend of a class:
class FriendClass
{
...
};
class NewClass
{
public:
friend class FriendClass; // declares
// entire class FriendClass as a friend
// of this class

};
Friend Class
Friend Class

• We could also have declared beta to be a class before the alpha class
specifier, as in previous examples.
• class beta;
• and then, within alpha, referred to beta without the class keyword:
• friend beta;
SUMMARY

• Standalone Friend Function


• Friend Class

You might also like