Friend Function
Friend functions in C++ are a special type of functions that are granted access to private and protected members of a class, even though they are not members of that class.
Key points about friend functions:
Declaration: Friend functions are declared inside the class definition using the
friend
keyword, but they are not member functions of the class.Access: They can access private and protected members of the class without being a member of that class.
Scope: They are not in the scope of the class, and they don't have a
this
pointer.Declaration vs. Definition: The function can be declared as a friend in the class definition, but the actual function definition is outside the class.
Cannot be inherited: Friendship is not inherited, meaning if a base class has a friend function, it doesn't automatically become a friend of the derived class.
Here's a simple example to illustrate friend functions:
Run it here.
In this example:
getBoxVolume
is a friend function of theBox
class. It can access private members ofBox
.BoxPrinter
is a friend class ofBox
. All its member functions can access private members ofBox
.The
getBoxVolume
function andBoxPrinter::printBoxDimensions
method can accesswidth
,height
, anddepth
directly, even though they're private.
Use cases for friend functions:
When you need a function to have access to private members of a class, but you don't want it to be a member function.
For operator overloading, especially when the left-hand operand is not an object of the class (like stream insertion operators).
To allow a function to work intimately with two different classes.
Last updated