Friend Class in C++ Programming
The given C++ program demonstrates the use of friend classes in C++.
- The program starts by including the necessary header files and defining two classes A and B. Class A has a private data member x which is initialized to 10. The class A also has a friend declaration for class B.
- Class B has a public object o of class A and a member function display(). The display() function prints the value of x of the o object of class A.
- In the main() function, an object obj of class B is created, and the display() function of class B is called, which displays the value of x of the o object of class A.
- Since class B is declared as a friend of class A, it has access to the private data member x of class A. This is demonstrated in the display() function of class B.
- Friend classes are useful when we want to provide access to private members of a class to another class. In this case, class B is a friend of class A, so it has access to the private member x of class A.
- The program ends by returning 0 from the main() function, indicating that the program ran successfully.
Source Code
#include<iostream>
using namespace std;
//Friend Class
class B;
class A
{
private:
int x=10;
friend B;
};
class B
{
public:
A o;
void display()
{
cout<<"X : "<<o.x;
}
};
int main()
{
B obj;
obj.display();
return 0;
}
Output
X : 10
To download raw file
Click Here