DEV Community

Cover image for Friend Class
Sakshi
Sakshi

Posted on

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. For example, a LinkedList class may be allowed to access private members of Node.

A friend class can access both private and protected members of the class in which it has been declared as friend.

#include <iostream>
using namespace std;




class Bestfriend1 
{


public:
int age;

private:
string purse;


public:

Bestfriend1 () 
  {

age = 14;

purse = "pink";

} 

void demo () 
  {

cout << "I am " << age << " years old\n";

cout << "I have " << purse <<
      " purse and I don't share it with anyone except my friend\n";

} 
friend class Bestfriend2;

//bestfriend2 is its friend
//it cant do anything except being 
//a frnd here, as it is declared and defined before its frnd //class
};



class Bestfriend2 
{


public:
int age;

private:
string dress;


public:
Bestfriend2 () 
  {

age = 14;

dress = "lilac";

} 
void show (Bestfriend1 & bf) 
  {

cout << "I am " << age << " years old\n";

cout << "I have " << bf.purse << " purse and " << dress << " dress\n";

} 
friend class Bestfriend1;

//it can access members of bestfriend1

};



class Stranger
{

public:
int age;

string dress;

string purse;


Stranger ()
  {

age = 14;

dress = "purple";

purse = "blue";

} 

void show ()
  {

cout << "I am " << age << " years old\n";

cout << "I have " << purse << " purse and " << dress << " dress\n";

} 

};




int
main () 
{

Bestfriend1 bf1;

bf1.demo ();

Bestfriend2 bf2;

bf2.show (bf1);


Stranger s1;

s1.show ();

return 0;

}



Enter fullscreen mode Exit fullscreen mode

Object

I am 14 years old
I have pink purse and I don't share it with anyone except my friend
I am 14 years old
I have pink purse and lilac dress
I am 14 years old
I have blue purse and purple dress

Enter fullscreen mode Exit fullscreen mode

Top comments (0)