What is friend class in C++? Show by C++ Code example

Answer includes friend class in C++ using a C++ code example and uses. Rather that defining it lets describe friend class by example and understand definition..

Answer:

Mainly, friend class is used for encapsulation (data hiding). If we want some class to keep private variables/data visible to some specific class and don’t want it to be visible to the rest of the world. We should be using friend class as a best solution.

For example, let’s have two classes i.e class A and Class B. We want object int option” of class A to be initialized by class B’s method first and then proceed.

class A{
private:
       int option;
       friend class B;
};
Friend class – C++ Program Example :
#include
using namespace std;

//Friend class example
class ColourOptions{

public:
void customColour(int option){
this->option =option;
}
private:
int option;
friend class Shape;
};

class Shape{
public:
Shape(){
options_.option =1;//set default colour
}

ColourOptions &Option(){
return options_;
}
int findShapes(){
//algorithm to find bule shapes
return this->options_.option; // just checking if we will be able to set custom colour here
}

private:
ColourOptions options_;
};


int main(){

Shape _shape;
int red =_shape.findShapes();
cout<<"Colour is "<<red<<"\n";
_shape.Option().customColour(5);

int blue =_shape.findShapes();

cout<<"Colour is "<<blue<<"\n";
_shape.Option().customColour(10);

int green =_shape.findShapes();

cout<<"Colour is "<<green<<"\n";

return 0;
}
What is friend class in C++? Show by C++ Code example
Scroll to top