Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Language: C++
Expertise: Intermediate
Jun 11, 1998

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 function

class 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.
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date