Friend Classes

Whole classes can also be made into friends to grant full access to another class's protected and private members, by declaring the keyword friend followed by the keyword class and then the identifier name of the class you wish to make into a friend.

 

Syntax:

friend class classOne ;

 

This will allow all members within the class in which it is declared to be accessed by the friend classOne.

 

The friendship is not mutual, and just because the original class may have declared its friend it does not mean that it will be able to access members of the friend, unless the friend has explicitly reciprocated the friend declaration back to it. All friends must be explicitly specified, and they do not transfer between one another.

 

#include <iostream>
#include<string>
using namespace std;

class classA {

	private:
		string secret ;
		friend class classB;  //declare a friend class

	public:
		classA() : secret("precious"){ }  //using initialiser list to assign value to secret
		void printMe() { cout << secret << endl; }
};

class classB {
	public:
		void change( classA &changeMe, string toChange ){
			changeMe.secret = toChange; //note classA's secret is being directly accessed
		}
};

int main() {
	classA master;  //create object of classA data type
	classB servant; //create object of classB data type

	master.printMe(); //use method in classA

	servant.change( master, "rotten" ); //use classB method to change classA value

	master.printMe();
}

Compile & Run:

precious 

rotten

Leave a Reply