devxlogo

That’s what friends are for

That’s what friends are for

A class can declare external functions or other classes as friends. Friendship grants full access to all of the grantor’s members, even private and protected ones:

 void encrypt (string & rep) {/*..*/} //global functionclass spy { 		public:			static void transmit(const string& rep) { /*..*/}		//...	};class secret {		friend class spy;//spy can access all members of 'secret'		friend void encrypt(string & rep);//...and so can encrypt	private:		string report; 	public:		void scramble() { ::encrypt(report); }		void transmit() const { spy::transmit(report); }};

Notes about friendship:

  1. A friend declaration exposes implementations details of its class, so it should be used wisely. However, friendship has the advantage of allowing code re-use in a simple manner; in fact, many of the standard functions and overloaded operators are used in standard containers (like string<>) by means of friendship.
  2. Friendship is not inherited, so non-public members of any class derived from secret are not accessible to spy and encrypt.
See also  Does It Make Sense to Splurge on a Laptop?
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist