Chapter 3.3

Friend Class and Friend Function

AmazonThe sole goal of having friends is to allow direct access to private data members of a class object. Friends come in two forms: friend classes and friend functions.

Let’s first discuss friend classes. Inside a class, you can declare other classes to be its friends. Doing so allows those classes to access its private members directly. Here is a sample program illustrating this concept:

As we can see, without declaring teacher to be a friend of student’s, you are not allowed to use the dot notation to access student’s private members. You can comment out the first line inside student and see what happens when you compile. An alternative to being able to use the dot notation to access student’s private members is to simply declare its data members to be public but it is not recommended.

After we see how friend classes work, let’s now see how friend functions work. Here is a sample program using this feature:

As we can see, both showgpa() and main() can access the private members of student by using the dot notation. To make a function a friend to a class, you need to give the name, the return type, and the parameter types of the function, as the example shows. If you comment out the first two lines inside student and recompile, the compiler will complain.

To sum up, a friend function or a class has the same access privileges as a member function of the class it is friends with.