[ fromfile: friends.xml id: friends ]
Now that you know about accessibility rules, you need to know how to occasionally break them.
The friend mechanism makes it possible for a class to allow nonmember functions to access its private data.
The keyword friend
is followed by a class or a function declaration.
friend
declarations are located inside a class definition.
Here are some syntax examples.
class Timer { friend class Clock; friend void Time::toString(); friend ostream& operator <<(ostream& os, const Timer& obj); [...] private: long m_Elapsed; };
A friend
can be a class, a member function of another class, or a nonmember function.
Typically, friend
functions are used for two purposes.
For Factory methods when you want to enforce creational rules (Section 16.1) on a class.
For global operator functions such as operator<<()
and operator>>()
when you do not want to make the operator a member function, or do not have write-access to the class definition.
Generated: 2012-03-02 | © 2012 Alan Ezust and Paul Ezust. |