Become a friend through Inheritance C ++

Let's say I have two classes

Widget ^ | Window 

and I have another class:

Defined as follows

 class Application { public: ... private: friend Widget; }; 

This will prevent Window from accessing secure applications and private members. Is there a way to do this without declaring a window and any subsequent β€œwidget” as a friend of the application?

+4
source share
3 answers

No, It is Immpossible.

friend ship is not inherited.

In addition, friend indicates a deliberate strong connection between two objects. So if your design really requires such a strong connection, make them friend s. friend ship breaking encapsulation is too wrong concept.

+4
source

Will defining some methods in the base class for call forwarding to the application do the job?

Eg.

 class Application { public: ... private: friend Widget; void PrivateMethod1(); }; class Widget { protected: void ApplicationPrivateMethod1() { /* forward call to application.PrivateMethod1(); */ } }; class Window : Widget { void SomeMethod() { // Access a friend method through the forwarding method in the base Widget class ApplicationPrivateMethod1(); } }; 
+3
source

If the inherited methods are the only ones that need access to the application class, then you can declare the individual methods as friends and until the window class overrides them, they can use these methods with access to a friend.

0
source

Source: https://habr.com/ru/post/1397214/


All Articles