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! |
Hold your calendar on January 30, 2008 for this free webcast on the new i5/OS. Rational's Enterprise Modernization products will be discussed at this webcast as they help to drive the application development environment for this new System i OS. <br />And learn how i5/OS will take you to the next step of efficient, resilient business processing. You will hear about the new i5/OS capabilities as it will be the most significant i5/OS release in years. If you cannot join the webcast on 1/30/08 you can still use this link to listen to the replay.<br /> FREE! Go There Now!
|
|
|
|
Effective governance for lean development isn’t about command and control. Instead, the focus is on enabling the right behaviors and practices through collaborative and supportive techniques. Hear from Scott Ambler on how it is far more effective to motivate people to do the right thing than it is to force them to do so. Learn how to form a lightweight, collaboration-based framework that reflects the realities of modern IT organizations. FREE! Go There Now!
|
|
|
|
Join this webcast to see how IBM Data Studio Developer and pureQuery can take the pain out of Java data access. uApplications developed using both Java and SQL have become a common requirement. Database connectivity using Java Database Connectivity (JDBC) to create an application is a multi-step tedious process, and tooling that covers both SQL and Java has been unavailable, until now. IBM Data Studio introduces the pureQuery platform: a high-performance, Java data access platform focused on simplifying the tasks of developing, managing, and optimizing database applications and services. FREE! Go There Now!
|
|
|
|
Join this Rational Talks to You teleconference on November 29 at 1:00 pm ET to participate in an interactive discusssion with Grady Booch around architecture and reuse. Get your questions answered! 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!
|
|
|
|
Try the latest version of IBM Rational Manual Tester V7.0.1 by downloading a free trial from IBM developerWorks. This manual test authoring and execution tool promotes test step reuse to reduce the impact of software change on testers and business analysts and addresses the needs of teams performing at least a portion of their testing manually. FREE! Go There Now!
|
|
|
|
Get a free trial download of the latest version of IBM Rational Method Composer V7.2 which helps you deliver customized yet consistent process guidance to your project teams and IT organization, and includes the latest version of IBM Rational Unified Process (RUP), which has provided process guidance to teams since 1996. 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!
|
|
|
|
Join this webcast to learn how IBM Rational's Functional Testing solution enables you to implement automation your way, at your pace, with your existing staff. In this webcast, you’ll learn how you can eliminate redundancy of manual test scripts, reduce errors, and increase test coverage through test automation. After this presentation you will understand how IBM Rational Functional Testing solution can streamline your manual testing and make test automation easily attainable. FREE! Go There Now!
|
|
|
|
All FREE IBM® developerWorks Tools! |