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..


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{
       int option;
       friend class B;
Friend class – C++ Program Example :
using namespace std;

//Friend class example
class ColourOptions{

void customColour(int option){
this->option =option;
int option;
friend class Shape;

class 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

ColourOptions options_;

int main(){

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

int blue =_shape.findShapes();

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

int green =_shape.findShapes();

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

return 0;

Related Posts