-1

I am confused on friend function and friend class in c++.

and in my coding experience, i never used friend. and even not found others's code contains friend.

i know the basic usage and idea of friend.

and typical demo is like:

#include <iostream>
using namespace std;
class Box
{
   double width;
public:
   friend void printWidth( Box box );
   void setWidth( double wid );
};
 
void Box::setWidth( double wid )
{
    width = wid;
}
 
void printWidth( Box box )
{
   cout << "Width of box : " << box.width <<endl;
}
 
int main( )
{
   Box box;
   box.setWidth(10.0);
   printWidth( box );
   return 0;
}

in this case, i dont know what's the meaning to use friend, i can define printWidth as:

void Box::printWidth() {
  cout << "Width of box : " << width <<endl;
} 

i think this will be better. and define it as friend wont make it more flexiable or universal.

So, can you provide a solid example to explain why i should use friend, or in what siutation, friend is a better or elegant solution?

xyhuang
  • 414
  • 3
  • 11
  • 1
    Your first example seemed reasonable. You want to give a free function access to your private member variables. The same is often used when overloading `operator<<` – Ted Lyngmo Feb 22 '21 at 11:07

1 Answers1

3

What you already seem to know...

This:

void Box::printWidth() {
  cout << "Width of box : " << width <<endl;
} 

Is a definition for a member function. But this:

friend void printWidth( Box box );

declares the free function printWidth as a friend of the class. Not everything must be / should be a member. If some other function needs access to private members you can make it a friend of the class while member functions already have access.


Example:

Some functions cannot be implemented as member functions. Maybe the most common example is an overload for std::ostreams <<:

std::ostream& operator<<(std::ostream& out, const Box& b) {
     out << ....
     return out;
}

// example usage:
Box b;
std::cout << b;

This operator<< is not a member of std::ostream and it cannot be a member of Box. Hence when it needs access to private members of Box it either needs to use getters or be a friend of Box.

(Note that even though << is neither member of std::ostream nor Box, it is considered as part of their interface. Implementing functions as non-member helps to keep the class definition small and simple.)

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185