devxlogo

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.

Charlie has over a decade of experience in website administration and technology management. As the site admin, he oversees all technical aspects of running a high-traffic online platform, ensuring optimal performance, security, and user experience.

See also  How Seasoned Architects Evaluate New Tech

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.