Intermediate Business Programming with C++

Friend Classes

One of the main principles behind OOP is encapsulation (i.e. the protection of private and protected members of a class). That is, only members of a class should be able to have access to the private members or the protected members. There may be times however in which it is desirable to overrule this OOP principle as well. See nofriend.cpp. The compiler can not compile this program, because a member function of class B is attempting to get access to a protected member of class A. This is not allowed.

In a previous discussion, this problem was handled by declaring a friend function. However what if there were several functions in the class B that need to have access to the protected or the private members of the class A. See friend0.cpp This program compiled in previous versions of C++ but it no longer compiles in Visual Studio .NET 2005 version of C++. It appears that while a class may have friend functions declared, they can not be methods for another class. While several class B's member functions could each be defined as friend functions another route must be followed.

The solution to this problem is friend classes. If a class B is a friend class of a class A, then all of the member functions of class B can access the private and the protected members of the class A. In order for this to happen, the following statement must be included in the definition of the class A:

friend class B;

See friend.cpp Notice that this program not only compiles but runs. In this example the class B was declared to be a friend in the public access section. It is also possible to declare B to be a friend in the private or the protected access section. See friend2.cpp.

By declaring the class B to be a friend class to the class A, the members of class B now have access to the private and protected members of the class A. This can be dangerous. However, notice that in order for this to happened, the class A has to give this permission. Class B can not get access to the class A members on its own.

There maybe times where it is desirable for the class B to have access to not only the private and protected member of the class A but also to the members of the class C. In an example of friend functions, a function was defined to have access to two different classes. This principle can be extended to the entire class rather than just a single function. If a class B is a friend class to two or more classes, then class B is said to have mutual friends. See friend1.cpp.

In earlier compilers it was necessary to declare the class B prior to its inclusion in the definition of the class A where it would be a friend class. This is not required in most compilers today.

Категории