Where would you use a friend function vs. a static member function?

Viewed 26682

We make a non-member function a friend of a class when we want it to access that class's private members. This gives it the same access rights as a static member function would have. Both alternatives would give you a function that is not associated with any instance of that class.

When must we use a friend function? When must we use a static function? If both are viable options to solve a problem, how do we weigh up their suitability? Is there one that should be preferred by default?

For example, when implementing a factory that creates instances of class foo which only has a private constructor, should that factory function be a static member of foo (you would call foo::create()) or should it be a friend function (you would call create_foo())?

15 Answers

Section 11.5 "The C++ Programming Language" by Bjarne Stroustrup states that ordinary member functions get 3 things:

  1. access to internals of class
  2. are in the scope of the class
  3. must be invoked on an instance

friends get only 1.

static functions get 1 and 2.

Friend functions (and classes) can access the private and protected members of your class. There's rarely a good case for using a friend function or class. Avoid them in general.

Static functions may only access static data (that is, class-scoped data). They may be called without creating an instance of your class. Static functions are great for circumstances you want all of the instances of your class to behave the same way. You can use them:

  • as callback functions
  • to manipulate class-scoped members
  • to retrieve constant data that you don't want to enumerate in your header file
  • Static functions are used when you want a function that is the same for every instance of a class. Such functions do not have access to "this" pointer and thus cannot access any non static fields. They are used often when you want a function that can be used without instantiating the class.

    Friend functions are functions which are not in the class and you want to give them access to private members of your class.

    And this(static vs. friend) is not a matter of using one vs the other since they are not opposites.

    The standard requires that operator = () [] and -> must be members, and class-specific
    operators new, new[], delete and delete[] must be static members. If the situation
    arises where we don't need the object of the class to invoke a function, then make
    the function static. For all other functions:
    if a function requires the operators = () [] and -> for stream I/O,
    or if it needs type conversions on its leftmost argument, or if it can be implemented using the class' public interface alone, make it nonmember ( and friend if needed in the first two cases)
    if it needs to behave virtually,
    add a virtual member function to provide the virtual behaviour
    and implement in terms of that
    else
    make it a member.

    A static function is a function that does not have access to this.

    A friend function is a function that can access private members of the class.

    You would use a static function if the function has no need to read or modify the state of a specific instance of the class (meaning you don't need to modify the object in memory), or if you need to use a function pointer to a member function of a class. In this second instance, if you need to modify the state of the resident object, you would need to pass this in and use the local copy. In the first instance, such a situation may happen where the logic to perform a certain task is not reliant on an object's state, yet your logical grouping and encapsulation would have it be a member of a specific class.

    You use a friend function or class when you have created code that is not a member of your class and should not be a member of your class, yet has a legitimate purpose for circumventing the private/protected encapsulation mechanisms. One purpose of this may be that you have two classes that have need of some common data yet to code the logic twice would be bad. Really, I have only used this functionality in maybe 1% of the classes I've ever coded. It is rarely needed.

    A friend function can not be inherited while a static function can be. So when an aim can be achieved with both static function and friend function, think that whether you want to inherit it or not.

    Static function can be used in many different ways.

    For example as simple factory function:

      class Abstract {
      private:
        // no explicit construction allowed
        Abstract(); 
        ~Abstract();
    
       public:
         static Abstract* Construct() { return new Abstract; }
         static void Destroy(Abstract* a) { delete a; }
       };
    
       ...
       A* a_instance = A::Conctruct();
       ...
       A::Destroy(a_instance);
    

    This is very simplified example but I hope it explains what I meant.

    Or as thread function working with Your class:

     class A {
    
     public:
        static void worker(void* p) {
                A* a = dynamic_cast<A*>(p);
                do something wit a;
        }   
     } 
    
     A a_instance;
     pthread_start(&thread_id, &A::worker, &a_instance);
     .... 
    

    Friend is completely different story and they usage is exactly as described by thebretness

    Here is what I think it is:

    Friend function- when you need access to a different class member, but the classes are not related. Static function- when you no not need access to the 'this' pointer. But, I have a feeling there is more to it....

    1. Static data members always share the memory.
    2. only static function can used static data members.
    3. static member function can be called with class name.
    4. They must be defined outside of the class when we create a object of static member or member function in the class. It will automatically initialize the value.
    5. It always used keyword static.
    6. Static members can share by all the objects.
    7. Type and scope of data members and member function is outside of the class.
    8. A static member variable must be defined outside of the class.
    Related