Friends to a Class in C++

Estudies4you
Friends to a Class
Q16. Write about friends to a class.
Answer: 

Friends to a Class
A class which is preceded by a keyword friend is called as friend class. The friend class is accessed by all the member functions of another class, When a class is declared as friend to another class it does not mean that these two classes are exchangeable. That is, these classes does not have any ability to exchange data with another.
If a class is declared as friend class, it can access the private members of another class. However, the other class cannot access the private members of friend.
Example
#include<iostream.h>
#include<conio.h>
//using namespace std;
//class exampleample2 //forward declaration
class example1
{
private:
int x;
public:
example (int b)
{
x=b;
}
friend class example2;
};
class example2
{
public:
void xyz(example1 &p)
{
cout<<"The value of x in example in class is:"<<p.x<<endl;
}
};
int main()
{
clrscr();
example1 e1(10);
example2 e2;
e2.xyz(e1);
getch();
return 0;
}


Output
Friends to a Class in C++

The above program displays the multiples of x from friend class. Initially, two classes named as examplel and example2 are declared. Example1 is defined with one private variable and one public member function example1() is used to read the value of x. Then friend class declaration in class one is as follows,
friend class example2.
Here, friend is the keyword, example is name of the class. The statement is terminated by semicolon.
In friend class(example2) the private class variables of class example1 are accessed. But, class example1 does not have the ability to access private members of friend class.
To Top