Friend Class Example in C++

If we make the entire class as a friend the automatically all the member functions of the class become friends. For class B to be a friend of class A. The class A must explicitly declare class B is its friend in the public section

Simple Program for Friend Class Using C++ Programming

#include<iostream> using namespace std; //class sample2 //forward declaration class sample1{ int a; public: sample1(int x){ a = x; } friend class sample2; }; class sample2 { public: void abc(sample1 &p){ cout<<"The value of a in sample2 class :"<<p.a<<endl; } }; int main(){ sample1 s1(5); sample2 s2;; return 0; }


The value of a in sample2 class :5

Explanation of the program

Here sample1 and sample2 are 2 classes and sample2 is a friend of sample1. Hence, sample2 can access all the private data members and member functions of the sample1 class.