Professional Documents
Culture Documents
Friend Function
Friend Function
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.
#include <iostream>
using namespace std;
class Box int printLength(Box b) int main()
{ { {
private: b.length += 10;
int length; return b.length; Box b;
public: } cout<<"Length of box:
Box(): length(0) { } "<< printLength(b)<<endl;
friend int
printLength(Box); //friend return 0;
function }
};
Let's see a simple example when friend void min(A,B); // if(a.x<=b.y)
the function is friendly to two friend function. std::cout << a.x << std::endl;
classes. }; else
class B std::cout << b.y << std::endl;
#include <iostream> { }
using namespace std; int y; int main()
class B; public: {
// forward declarartion. void setdata(int i) A a;
class A { B b;
{ y=i; a.setdata(10);
int x; } b.setdata(20);
public: friend void min(A,B); min(a,b);
void setdata(int i) // friend function
return 0;
{ };
}
x=i; void min(A a,B b)
} {
C++ Friend class using namespace std; {
A friend class can access cout<<"value of x is :
both private and class A "<<a.x;
protected members of }
the class in which it has {
been declared as friend. int x =5; };
friend class B; // int main()
Let's see a simple friend class. {
example of a friend class. }; A a;
class B B b;
#include <iostream> { b.display(a);
public: return 0;
void display(A &a) }