What are Friend classes and Friend Functions?
A class declared as a Friend class has access to private members of the class-
A friend function is not a member of the class, but has access to the non-public members of the class. In general, friend functions are frowned upon in C++ because it breaks the natural encapsulation. One of the best uses of friend functions is with operator overloading.
// Example of the friend class
class YourClass
{
friend class YourOtherClass; // Declare a friend class
private:
int topSecret;
};
//Example of friend functions
// Point.h file
class Point {
friend GetCoordinates();
public:
Point();
Point(int x1, int y1)
. . .
// Point.cpp file
. . .
GetCoordinates();
{
}
C++ FAQ Home