- Home
- Course Category
- Course Result
- Course Detail
Hot Line: 0124-2383121
Course Introduction
Friend Class
Friend Class A friend class can access private and protected members of other class in which it is declared as friend.
It is sometimes useful to allow a particular class to access private members of other class.
Source Code:Friend Class
/* C++ Program - Friend Class */
#include <iostream>
using namespace std;
class A {
private:
int a;
public:
A() { a = 0; }
friend class B; // Friend Class
};
class B {
private:
int b;
public:
void showA(A& x)
{
// Since B is friend of A, it can access
// private members of A
cout << "A::a=" << x.a;
}
};
int main()
{
A a1;
B b;
b.showA(a1);
return 0;
}
When the above code is compiled and executed, it produces the following result −
A::a=0