What is Friend?

A friend is Special One
What is the difference between a friend and a non-friend?
A friend has privileges to your private and protected stuff

Friend Function in C++
Friend Function in C++

 

What is Friend Function

A friend function in C++ is a function that is preceded by the keyword “friend”. When the function is declared as a friend, then it can access the private and protected data members of the class.

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.
/*

Objective: Demonstrate Friend Fucntion


*/


#include <iostream.h>
#include <conio.h>

class Box
{
	private:
	int width;
	public:
	void setData(int x)
	{
	     width=x;
	}
	friend void display(Box b);

};

void display(Box b)
{
	cout<<"I am box and my width is "<<b.width<<endl;
}

void main()
{
	clrscr();
	Box b1;
	b1.setData(100);
	display(b1);
	getch();

}      
Friend Function in C++

Leave a Reply

Your email address will not be published. Required fields are marked *