Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 8

Friend Function in C++

• A friend function is a function of the class


defined outside the class scope but it has the
right to access all the private and protected
members of the class.
• The friend functions appear in the class
definition but friends are not the member
functions.
• The function is not in the scope of the class to which it has
been declared as a friend.

• It cannot be called using the object as it is not in the scope


of that class.

• It can be invoked like a normal function without using the


object.

• It cannot access the member names directly and has to use


an object name and dot membership operator with the
member name.
• The friend function is declared using friend keyword.

• It is not a member of the class but it is a friend of the class.

• As it is not a member of the class so it can be defined like a


normal function.

• Friend functions do not access the class data members


directly but they pass an object as an argument.
Syntax for the declaration of a friend function.

class class_name      
{      
    friend data_type function_name(argument/
s);            // syntax of friend function    
};      

data_type function_name(argument/s)
{
//body of friend function
}
• Program is discussed in class lecture, refer
there.
• A friend function can become friend to more
than one classes.

• Program is discussed in class lecture, refer


there.
Friend class
Class A
{
friend class B;
};
Means class B is friend to class A but not vice-versa.
The member functions of class B can access the data
members of class A but not vice-versa.

Program is discussed in class lecture, refer there.

You might also like