Sunday, March 23, 2008

Friends in C++

Friend functions and classes are not the most common of C++ features but there are situations where the friend keyword is useful.

A friend is something that allows your class to be accessed by a different class or function. The friend keyword can be used in 2 cases, to declare a friend function or a friend class.

When you declare a friend function in your class, then it can do anything that a member function of the class can do. So in the following, friendFn() can do anything to the object passed to it that memberFn() can do.


At the end of the above example, the private popObject data mData is 6. Note that the object passed is only changed as it is passed as a reference. If the function declaration for friendFn was as follows:
friendFn(PopularClass pObject, int x);
then friendFn() would have made a copy of the object passed and changed its member variable.


Friend Classes follow along the same principle, they allow another class to have access to the data in a class. So in the following, PopularClass allows the class FriendClass access to its private data. So when fObject.addVals(popobject) gets its hands on popObject it is allowed access to the private data so that it can add the private data from both its own class (which it, of course, always had access to) and the passed in popObject which is an object of a different class.



So friends can be useful if you treat them right (sorry, way too corny I know...)

No comments: