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! |
Learn field-tested SOA principles, methodology, technology and implementation from the global SOA market leader - in a new e-book by an IBM SOA expert. Written by IBM Certified SOA Solution Designer Bobby Woolf, "Exploring IBM SOA Technology & Practice" is the ultimate insider's guide to SOA - a PDF e-book packed cover to cover with IBM's specific advice on how to make your SOA implementation a success. FREE! Go There Now!
|
|
|
|
Learn how you can extend modern application lifecycle management to IBM System z through the IBM Rational Software Delivery Platform (SDP). The Did you say mainframe? e-kit includes podcasts, webcasts, tutorials, white and red papers, demos, and articles designed to help ease the challenges of modernizing your enterprise. This complimentary kit for mainframe developers is a practical, how-to guide for making the most of an existing development environment, including the skills and infrastructure already in place at an established enterprise. 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!
|
|
|
|
Listen to this webcast to get an overview of Info 2.0 and a technical demo of how to quickly build an enterprise mashup. IBM's Info 2.0 technology leverages emerging Web 2.0 technologies such as mashups, feeds, AJAX, and JSON in order to simplify assembly of information using feeds and services. Come learn about the technical elements of Info 2.0 including the Feed Generation framework, Mashup Engine, and mashup assembly components. Learn how to pull information from databases, departmental information, and the Web to create mashups critical to your company’s success. We will also discuss best practices to help you get started. FREE! Go There Now!
|
|
|
|
Portfolio Management is about effectively managing portfolio value by aligning portfolio investments with business goals. This complimentary e-kit provides a collection of materials that can help you understand how IBM Rational enables and automates best practices for improved governance and clear visibility into portfolio and project performance across the entire IT project lifecycle. FREE! Go There Now!
|
|
|
|
Join this Rational Talks to You teleconference on December 11 at 1:00 pm ET to get tips on building your own plugins with Rational Method Composer. Get your questions answered! FREE! Go There Now!
|
|
|
|
Discover how Rational tools and best practices for testing can make your job easier. The new Rational Testing eKits provide you with valuable resources – including demos, webcasts, tutorials, and articles – that help you address your specific testing needs across the software lifecycle. Five new eKits are available covering the topics of Requirements and Test Management, Functional Testing, Performance Testing, Code Quality and Embedded Systems, and SOA and Web Services Testing. FREE! Go There Now!
|
|
|
|
Join the IBM Watchfire team for an informative discussion on techniques and best practices to proactively manage Web application security and how to effectively build application security testing into the software development lifecycle (SDLC). In this Software Delivery Platform webcast you will learn: How to better understand potential web application security vulnerabilities, best practices and how to effectively integrate application security testing into the software development lifecycle, the importance of detecting and removing software vulnerabilities during application development. FREE! Go There Now!
|
|
|
|
The Eclipse community is constantly working to extend Eclipse's functionality. In this webcast, learn about some of the most important and feature-rich projects under development. From multi-language support to plug-in development, tune in to see what Eclipse is capable of now. FREE! Go There Now!
|
|
|
|
Explore how Rational and WebSphere software enable enterprise documentation in SOA environments. Specifically, a new integration between IBM WebSphere® Business Modeler and IBM Rational® Method Composer software can help technical writers more easily keep enterprise operations manuals in sync with changes that are made to business processes, resulting in more accurate and timely documentation that benefits the entire enterprise. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |