Matthew Hoggan
Matthew Hoggan

Reputation: 7594

Becoming a friend through Inheritance C++

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?

Upvotes: 4

Views: 159

Answers (3)

realgenob
realgenob

Reputation: 95

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.

Upvotes: 0

Scott Langham
Scott Langham

Reputation: 60311

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();
   }
};

Upvotes: 3

Alok Save
Alok Save

Reputation: 206546

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.

Upvotes: 4

Related Questions