C++ Tricks of the Trade: Friend Functions
By Kais Dukes
Introduction
This new "C++ Tricks of the Trade" series of articles will show you how to write efficient yet maintainable C++ code, as well as explaining how to avoid common programming pitfalls.
In this introductory article, Kais discusses how to use friend functions to enhance a class interface.
Friendly Friends
By using the friend keyword, a class can grant access to non-member functions or to another class. These friend functions and friend classes are permitted to access private and protected class members. There are places where friends can lead to more intuitive code, and are often needed to correctly implement operator overloading.
If encountering friend functions for the first time, you might feel slightly uneasy since they seem to violate encapsulation. This feeling may stem from the fact that a friend function is not strictly a member of the class.
By thinking of a friend function as part of the classs public interface, you can get a better understanding of how friends work. From a design perspective, friends can be treated in a similar way to public member functions. The concept of a class interface can be extended from public members to include friend functions and friend classes.
Put another way:
Friend functions do not break encapsulation; instead they naturally extend the encapsulation barrier.
Friend Functions
Friend functions can be declared anywhere within a class declaration, but it is common practice to list friends at the beginning of the class. The public and protected keywords do not apply to friend functions, as the class has no control over the scope of friends.
To see where a friend function would useful, suppose we are constructing a class to represent a rational number as a pair of integers. If we want to use rational numbers in the same way as intrinsic types like a double or an int, then it would be reasonable to be able to write:
CRational r(2, 3);
cout << r << endl;
In order to do this, we need to stream a rational object to an STL ostream by overloading the binary << operator:
class CRational
{
friend ostream &operator<<(ostream &out, const CRational &r);
public:
CRational(const int nNumerator, const int nDenominator);
~CRational();
// ...
};
The friend function gets full access to the members of CRational, in order to do its job of writing to an ostream:
ostream &operator<<(ostream &out, const CRational &r)
{
// Access private members of CRational to display r.
// ...
return out;
}
This operator overload could be declared as a non-friend function, but that would require using get() and set() members to reach the internals of the rational class. It is considered good practice to declare the operator<< function as a friend, even if get/set members exist. When reading through the CRational class declaration it is clear that the operator<< function should be treated as part of the classs public interface when marked as a friend.
Another reason for using a friend function is one of efficiency: directly accessing data members saves the overhead of using get/set members, if the compiler has not inlined these.
Commutative Operators
Overloading operator+ allows the rational class to behave more like an intrinsic data type. To add two rational numbers, we can overload the operator as a class member:
const CRational CRational::operator+(const CRational &r)
{
// add *this to r, and return the result by value.
// ...
}
The operator+ function can also be overloaded to handle the addition of a rational, and a non-rational type. If n is an integer, and r is a rational then we could implement r + n as a class member:
const CRational CRational::operator+(const int n)
{
// add *this to n, and return the result by value
// ...
}
Since operator+ is an example of a commutative operator, we would expect r + n to have the same semantics as n + r. In the second case we need to use a non-member function:
class CRational
{
friend const CRational
operator+(const int n, const CRational &r);
// ...
}
This function could be written as a non-friend function, provided that get/set member functions are used. Doing so would turn the function into a plain non-member function, and so it would not be clear how it interacts with the class. By using a friend function, readers of the class declaration see that operator+ forms part of the CRational interface, and is semantically part of the class.
Friends and Virtual Functions
A problem with friends is that class member functions can be virtual while non-member functions cant. The equivalent of a virtual friend function is useful when deriving from a class that has a friend function.
An example of where the equivalent of a virtual friend would be useful is if serializing an entire class hierarchy. The trick in doing this is to turn the friend function into a lightweight inline proxy function, which forwards the request back to the class. For example, consider the simple base class:
class CPerson
{
friend ostream &operator<< (ostream &out, CPerson &person);
// ...
protected:
virtual ostream &display(ostream &out);
// ...
};
The friend function forwards the display request back to the CPerson class. Note that we pass an instance of CPerson by reference:
inline ostream &operator<< (ostream &out, CPerson &person)
{
return person.display(out);
}
In a class hierarchy using the base CPerson class, each derived class has its own implementation of the display function:
class CBob : public CPerson
{
protected:
virtual ostream &display(ostream &out)
{
out << "Bob";
return out;
}
};
This is just as efficient as using a virtual friend function (if such a thing existed) since a good compiler will replace a call to operator<< with a call to the display function, which each derived class implements.
Friend Classes
As well as choosing a non-member friend function, a class has two other possibilities for its friends. A class can declare a member function of another class as a friend, or declare another class as a friend class.
Friend classes are used in cases where one class is tightly coupled to another class. For example, suppose we have a class CPoint that represents a coordinate, and a class CPointCollection that holds a list of points. Since the collection class may need to manipulate point objects, we could declare CPointCollection as a friend of the CPoint class:
// Forward declaration of friend class.
class CPointCollection;
// Point class.
class CPoint
{
friend CPointCollection;
public:
CPoint(const double x, const double y) :
m_x(x),
m_y(y)
{
}
~CPoint(void)
{
}
// ...
private:
double m_x;
double m_y;
};
Since the collection class is a friend of CPoint, it has access to the internal data of any point object. This is useful when individual elements of the collection need to be manipulated. For example, a set method of the CPointCollection class could set all CPoint elements to a particular value:
class CPointCollection
{
public:
CPointCollection(const int nSize) :
m_vecPoints(nSize)
{
}
~CPointCollection(void);
void set(const double x, const double y);
// ...
private:
vector<CPoint> m_vecPoints;
};
The set member can iterate over the collection and reset each point:
void CPointCollection::set(const double x, const double y)
{
// Get the number of elements in the collection.
const int nElements = m_vecPoints.size();
// Set each element.
for(int i=0; i<nElements; i++)
{
m_vecPoints[i].m_x = x;
m_vecPoints[i].m_y = y;
}
}
One thing worth noting about friend classes is that friendship is not mutual: although CPointCollection can access CPoint, the converse is not true. Friendship is also not something that is passed down a class hierarchy. Derived classes of CPointCollection will not be able to access CPoint. The principle behind this is that friendship is not implicitly granted; each class must explicitly choose its friends.
Conclusion
Friend functions and friend classes allow a class interface to be extended in a natural and efficient way. For some problems, friend functions lead to more intuitive code, while friend classes are needed when two classes are tightly coupled. Non-member friend functions are especially useful for implementing operator overloading, a good example being operator<<.
Friend functions do not break encapsulation, but rather enhance a class interface. Although this is the case, friends should be used judiciously; a member function will often do just as well. As a general rule of thumb, use member functions where possible, and friends where necessary. A well-designed project will not be free of friend functions, but will instead use them in places where non-members are naturally part of a class.
Top quality daily ASP, PHP and .NET articles, tutorials, news, reviews, interviews AND FREE EBOOKS! devArticles is the ultimate online resource for the serious web developer. Visit
http://www.devarticles.com today!
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |
More Web Development Articles
More By Developer Shed
developerWorks - FREE Tools! |
<a href="http://zeus.developershed.com/shonuff.php?blackbird=3853&zoneid=442&source=&dest=http%3A%2F%2Fwww.ibm.com%2Fdeveloperworks%2Fspaces%2Fjazz%3FS_TACT%3D105AGY31%26S_CMP%3DDEVSHED&ismap="><img src="http://images.devshed.com/corp/img/news/jazz01.gif" alt="developerWorks Jazz space" align="left"></a>You've heard the buzz about Jazz... want to know more about it from a developer's perspective? Check out the Jazz space on developerWorks. This space is an up-to-date resource for developers, including technical information about Jazz and products built on Jazz, like Rational Team Concert Express. The Jazz space includes content from a wide variety of sources, including links, feeds, and comments from experts. FREE! Go There Now!
|
|
|
|
Join this webcast, to learn how the Rational Process Library can help with compliance issues, drive process improvement, and assist in service-oriented architecture (SOA) or Agile development. We will take a peek into the Rational Process Library with content around software and systems engineering (including RUP), operations and systems management, program and portfolio management, and asset and SOA governance. FREE! Go There Now!
|
|
|
|
This whitepaper presents the benefits of successfully introducing static analysis into your organization using IBM Rational Software Analyzer. Additionally, it identifies some common pitfalls that can hinder the effective use of static analysis tooling as well as presents 10 simple strategies designed to help you quickly realize the value of static analysis using Rational Software Analyzer. FREE! Go There Now!
|
|
|
|
Learn to enable users to both rate existing animations and to combine existing animations into new snippets. This is the third in a series of three tutorials that chronicle the building of a site that enables collaborative discussion and animation building using Domino and OpenLaszlo. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial version of WebSphere Business Modeler Advanced V6.1.1, IBM’s premier business process modeling and analysis tool for business users that offers process modeling, simulation, and analysis capabilities. IBM WebSphere Business Modeler helps you visualize, understand, and document business processes for continuous improvement. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial of the latest release of IBM Lotus Sametime Standard V8.0. Lotus Sametime Standard V8.0 is a platform for unified communications and collaboration that combines security features with an extensible, open solution including integrated Voice over IP, geographic location awareness, mobile clients, and a robust Business Partner community offering telephony and video integration. FREE! Go There Now!
|
|
|
|
Visit IBM developerWorks to download a free trial version of IBM Rational Business Developer V7.1. Rational Business Developer offers rapid and simplified development of business applications and services through Enterprise Generation Language (EGL) tools, generating Java or mainframe solutions while shielding developers from technical complexities. FREE! Go There Now!
|
|
|
|
Join this webcast to discover the key requirements for successful change and release management. Learn how to extend your .NET environment to improve productivity and collaboration, and address core problems afflicting team development. In this webcast, we’ll review typical challenges faced by customers and how to resolve them with the IBM Rational Change and Release Management solution, including Rational ClearCase, Rational ClearQuest and Rational Build Forge. Replay is available for 9 months. FREE! Go There Now!
|
|
|
|
Regression testing -- in which code is thoroughly tested to ensure that changes have not produced unexpected results -- is an important part of any development process. But many testing environments neglect the terminal-based applications that still form the backbone of many industries. In this tutorial, you'll learn how the Rational Functional Tester Extension for Terminal-Based Applications works with other Rational Functional Tester to help test terminal-based applications quickly and easily. FREE! Go There Now!
|
|
|
|
Attend this launch webcast with Scott Hebner, Vice President of IBM Rational Marketing and Strategy, where he will overview Rational’s new offerings and programs to help customers accelerate software innovation on System z. He will discuss how these solutions help organizations extend their core business processes toward modern architectures such as SOA and web technologies to deliver business improvements that stand the test of time. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |