Search code examples
c++encapsulationfriendaccess-control

Alternative to friendship?


Is there any alternative to friendship in the following scenario?

I have a Window class which represents an UI window. Also, a WindowManager class, implemented as a singleton, manages all window objects in my application (renders the UI, dispatches events, etc.)

The WindowManager will have a public interface consisting of only its singleton instancing method and functions to render the UI and to dispatch an UI event.

I would also like Window objects to register with the WindowManager during construction and to de-register during destruction. The WindowManager::register and WindowManager::deregister methods will be either private or protected, because I do not want clients (other than Window objects) to be able use this interface.

Is there a method to avoid friendship between Window and WindowManager in this case? Perhaps a totally different way to achieve similar results?


Solution

  • Yes, but friendship is the best solution, since it's designed for this scenario.

    Another way is to make Window a member of WindowManager (note, this requires the new C++11 accessibility rules). Or have it derive from a member of WindowManager. Or have it derive from WindowManager itself.

    You can also put a private type inside Window, make a key type nested in Window which can only be constructed from that private type, and require passing an instance of that key type to WindowManager. This should work in pre-C++11 compilers.

    Of course, any approach can be bypassed using enough casting.