0% found this document useful (0 votes)
109 views

Friend Function

A friend function is not a member function of a class, but is granted access to private and protected members of that class. It can access private data members and member functions. It is declared inside the class but defined outside. A friend function is called like a regular function and does not require an object of the class to access its members.

Uploaded by

Soham Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
109 views

Friend Function

A friend function is not a member function of a class, but is granted access to private and protected members of that class. It can access private data members and member functions. It is declared inside the class but defined outside. A friend function is called like a regular function and does not require an object of the class to access its members.

Uploaded by

Soham Patil
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 11

Friend Function

Characteristics of a Friend function:


• 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.
• It can be declared either in the private or the
public part.
C++ friend function Example
#include <iostream>
using namespace std;
class Box
{
private:
int length;
public:
Box(): length(0) { }
friend int printLength(Box); //friend function

};
int printLength(Box b)
{
b.length += 10;
return b.length;
}
int main()
{
Box b;
cout<<"Length of box: "<< printLength(b)<<
endl;
return 0;
}
Program 2
#include <iostream>

class B; // forward declarartion.

class A
{
int x;
public:
void setdata(int i)
{
x=i;
}
friend void min(A,B); // friend function.
};
class B
{
int y;
public:
void setdata(int i)
{
y=i;
}
friend void min(A,B); // friend function
};
void min(A a,B b)
{
if(a.x<=b.y)
std::cout << a.x << std::endl;
else
std::cout << b.y << std::endl;
}
int main()
{
A a;
B b;
a.setdata(10);
b.setdata(20);
min(a,b);
return 0;
}

You might also like