Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 602
Dan Nestor Avatar asked Oct 28 '25 20:10

Dan Nestor


2 Answers

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.

like image 84
Ben Voigt Avatar answered Oct 30 '25 10:10

Ben Voigt


Using Friendship seems appropriate here.You want to indicate an Intentional strong coupling between the two classes, which is aptly indicated through friends.

More specifically, one class needs access to another classes's internals and you don't want to grant access to everyone by using the public access specifier.

The rule of thumb: is public is too weak and private is too strong, you need some form of selected access: either protected or friend.

Using Friendship is the Best solution here.

like image 35
Alok Save Avatar answered Oct 30 '25 10:10

Alok Save



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!