Friend functions and classes

Friend functions and classes are external functions or classes which are granted access to all members of a class. To my mind, this breaks encapsulation and shouldn’t be done. Maybe that’s just my years of Java speaking. Maybe I just need to get used tot eh C++ way of doing things.

Friend Functions

Consider the following code:

#include <iostream>
#include <string>

class Point {
    friend void print_point(const Point &point);
public:
Point(double x, double y);
~Point();

private:
    double x {};
    double y {};
};

void print_point(const Point &point) {
    std::cout << "Point [ x:" << point.x << ", y:" << point.y << " ]";
}

int main() {
    print_point(Point(10.5, 8.75));
    return 0;
}

The print_point function uses the private member variables of the Point class but that’s alright because the class declares it as a friend.

The friend keyword is followed by the entire function declaration including the return type.

  • Friend functions must exist!
  • The implementation can be in any translation unit. As long as it’s findable when linking. Typically, they’re put with the class implementation.
  • The class decides who it’s friends with.
  • There can be multiple friend functions and they can be overloaded.
  • The declaration can appear in either the public or private sections of the class.
  • Friend functions don’t have access to the this pointer.

Friend Classes

Consider the following code:

class Point {
    friend class ThreeDPoint;
public:
    Point(double x, double y);
    ~Point();

private:
    double x {};
    double y {};
};

class ThreeDPoint {
public:
    ThreeDPoint(double x, double y, double z);
    ~ThreeDPoint();

    void print_point(const Point & point) const;

private:
    double x {};
    double y {};
    double z {};
};

The point has declared the the ThreeDPoint class to be it’s friend so it can access it’s member variables. The kewords friend class are followed by the name of the class.

  • Friend classes must exist!
  • The external class implementation can be in any translation unit. As long as it’s findable when compiling and  linking.
  • The class decides who it’s friends with.
  • There can be multiple friend classes.
  • The declaration can appear in either the public or private sections of the class.
  • Friend classes don’t have access to the this pointer of the target class.

Just because ThreeDPoint is a friend of Point, doesn’t mean the same is true in reverse. Friendship is also not transitive.

 

 

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.