Friend Class in C++ Programming
OOPs in C++
In this lesson, we will understand what is Friend Class in C++ Programming and how to create them along with some examples.
What is Friend Class in C++?
The friend class is a class that can access the private and protected data members of other class without inheriting the class. It is declared inside a class with the keyword friend.
It can be declared either in the private or public section of the class.
Example
#include <iostream>
#include <string.h>
using namespace std;
class student
{
private:
int roll;
char name[30];
public:
// Constructor
student()
{
roll=1;
strcpy(name,"Martin");
}
// friend class
friend class marks;
};
class marks
{
private:
int eng;
int math;
public:
// Constructor
marks()
{
eng=89;
math=94;
}
void display(student &x)
{
cout<<"Roll: "<<x.roll<<endl;
cout<<"Name: "<<x.name<<endl;
cout<<"English: "<<eng<<endl;
cout<<"Math: "<<math<<endl;
}
};
int main()
{
student x;
marks a;
a.display(x);
return 0;
}
Output
Roll: 1 Name: Martin English: 89 Math: 94
In the above example, we have created two classes, student and marks. The marks class being declared as a friend class inside the class student can access the private data members of the class student.