W4L6
W4L6
Friend Function
Indranil Saha
CS253: Software Development and Operations Object-Oriented Programming Using C++ 1/6
Friend Function
A friend function of a class is defined outside that class’ scope but it has
the right to access all private and protected members of the class
Even though the prototypes for friend functions appear in the class
definition, friends are not member functions
A friend can be a class, in which case the entire class and all of its
members are friends
CS253: Software Development and Operations Object-Oriented Programming Using C++ 2/6
Friend Function
public:
double length;
friend void printWidth( Box box );
void setWidth( double wid );
};
CS253: Software Development and Operations Object-Oriented Programming Using C++ 3/6
Example: Friend Function
Friend function for the Box class
class Box {
double width;
public:
friend void printWidth( Box box );
void setWidth( double wid );
};
CS253: Software Development and Operations Object-Oriented Programming Using C++ 4/6
Example: Friend Class
CS253: Software Development and Operations Object-Oriented Programming Using C++ 5/6
Object-Oriented Programming Using C++
Friend Function
Indranil Saha
CS253: Software Development and Operations Object-Oriented Programming Using C++ 6/6