4

Lets say I have two classes

Widget
  ^
  |
Window

and I have another class Application:

Defined as follows

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

This will not give Window access to Applications protected and private members. Is there a way to accomplish this without declaring Window and any subsequent "Widget" as a friend of Application?

Matthew Hoggan
  • 7,402
  • 16
  • 75
  • 140
  • possible duplicate of [Friend scope in C++](http://stackoverflow.com/questions/437250/friend-scope-in-c) – Mat Feb 18 '12 at 17:35

3 Answers3

4

No it is not possible.

friendship is not inheritable.

Also, friendship indicates a intentional strong coupling between two entities So if your design indeed demands such a strong coupling go ahead and make them friends. friendship breaking encapsulation is a far too misunderstood concept.

Alok Save
  • 202,538
  • 53
  • 430
  • 533
3

Would defining some methods in the base class to forward calls to 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();
   }
};
Scott Langham
  • 58,735
  • 39
  • 131
  • 204
0

If the inherited methods are the only ones that need access to app class than you can declare the individual methods as friends and as long as the window class doesn't override them they can use those methods with friend access.

realgenob
  • 95
  • 5