Friend Class in C++

Friend Class:

C++ provides the friend keyword for major two purpose one for friend function and another for creating friend class. In this session we will talking about friend class that is inside a class, we can indicate that other classes will have direct access to protected and private members of the class. When granting access to a class, you must specify that the access is granted for a class using the class keyword:

friend class Faculty;

Note that friend declarations can go in either the public, private, or protected section of a class–it doesn’t matter where they appear. A class can also be declared to be the friend of some other class. When we create a friend class then all the member functions of the friend class also become the friend of the other class.


/*
Developed By: Prof. Vinod Pillai
vinodthebest@gmail.com
Friend Class.
*/

#include

using namespace std;

class A
{
int vala;

public:

void set(int tvala)
{
vala=tvala;
}
void display()
{
cout<<"\n The Value of a is:"<<vala;
}
friend class B;
};

class B
{
int valb;

public:

void set(int tvalb)
{
valb=tvalb;
}
void display()
{
cout<<"\n The Value of b is:"<<valb;
}

void sum(A ta)
{
valb=valb+ta.vala;
}
};

int main()
{
A aobj;

B bobj;

aobj.set(100);
bobj.set(200);

aobj.display();
bobj.display();

bobj.sum(aobj);
bobj.display();

return 0;
}

Leave a comment

Filed under C++

Leave a comment