Web Development

  Homes arrow Web Development arrow C++ Tricks of the Trade: Friend Functions
 Webmaster Tools
 
Base64 Encoding 
Browser Settings 
CSS Coder 
CSS Navigation Menu 
Datetime Converter 
DHTML Tooltip 
Dig Utility 
DNS Utility 
Dropdown Menu 
Fetch Content 
Fetch Header 
Floating Layer 
htaccess Generator 
HTML to PHP 
HTML Encoder 
HTML Entities 
IP Convert 
Meta Tags 
Password Encryption
 
Password Strength
 
Pattern Extractor 
Ping Utility 
Pop-Up Window 
Regex Extractor 
Regex Match 
Scrollbar Color 
Source Viewer 
Syntax Highlighting 
URL Encoding 
Web Safe Colors 
Forums Sitemap 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Contact Us 
Site Map 
Privacy Policy 
Support 
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
WEB DEVELOPMENT

C++ Tricks of the Trade: Friend Functions
By: Developer Shed
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 7
    2003-08-09

    Table of Contents:

    Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article
     
     

    SEARCH DEV MECHANIC

    TOOLS YOU CAN USE

    advertisement

    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 class’s 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 class’s 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 can’t. 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

       

    WEB DEVELOPMENT ARTICLES

    - On Page SEO for New Domains
    - Improve Your Site`s Speed
    - Safari Books Online Review
    - Creating an Estore From the Ground Up
    - Most Common SEO Mistakes Developers Make
    - Making the Most of Your Titles and Meta Desc...
    - Five Ways Using Flash Can Damage Your Site
    - A Web Designer`s Guide to Colors
    - Use Webstarts to Create a Free Site
    - More Than Just Looks. How Your Web Design C...
    - How to Design Content Pages
    - Mint Review
    - Make Your WordPress Website Look Professional
    - How to Create a Mobile Web Site
    - Meta Tags: Still Useful?

    Developer Shed Affiliates

     



    © 2003-2018 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap