What is "friend" keyword in C++ ?
Whenever we want to give access of private or protected members of a class to other class or function in such cases we give access to them with the help of "friend" keyword.Â
"friend" keyword is used to declare any class or function as friend class or friend function respectively.
What is friend function ?
Friend function is a function which can access the private and protected member data of class in which it is declared as friend and defined outside the scope of class without using scope resolution operator.
Syntax of declaring friend function:
class Class_Name
{
private:
int private_member;
friend data_type function_name(Class_Name obj_name);
}
// friend function definition
data_type function_name(Class_Name obj_name)
{
// function body
}
Example of friend function:
#include <iostream>
using namespace std;
class ClassA
{
private:
int num1, num2;
friend int add(ClassA a); // declaration of friend function
public:
void getdata()
{
cout << "Enter two numbers: ";
cin >> num1 >> num2;
}
};
// Definition of friend function add
int add(ClassA a)
{
int result;
result = a.num1 + a.num2;
return result;
}
int main()
{
ClassA obj;
obj.getdata();
cout << "Sum of two numbers is: " << add(obj);
return 0;
}
Output for example of friend function:
What is friend class ?
Friend class is a class which can access the private and protected member functions of other classes in which it is declared as friend. Once a class is declared as a friend class its all member functions becomes friend function.
Syntax of declaring friend class:
class MainClass {
friend class friendClass; //friendClass is a friend of MainClass
private:
dataType privateMember;
protected:
dataType protectedMember;
}
class friendClass {
public:
returnType someFunction(MainClass c)
{
c.privateMember = value; //private member of MainClass can be accessed
c.protectedMember = value; //protected member of MainClass can be accessed
}
}
Example of friend Class:
#include <iostream>
using namespace std;
class Point
{
friend class Triangle;
private:
int x, y;
};
class Triangle
{
public:
int Base(Point p)
{
return p.x = 5; // direct access to x, which is private member of Point class
}
int Height(Point p)
{
return p.y = 14; // direct access to y, which is private member of Point class
}
double Area(Point p)
{
return 0.5 * Base(p) * Height(p);
}
};
int main()
{
Point p;
Triangle t;
cout << "Area of triangle is: " << t.Area(p);
return 0;
}
Output for example of friend function:
#ENJOY CODING
Post a Comment
FOR ANY DOUBTS AND ERRORS FEEL FREE TO ASK. YOUR DOUBTS WILL BE ADDRESSED ASAP