开发者

C++ friend inheritance?

Does a subclass inherit, the main class' friend associations (both the main class' own and开发者_Python百科 other classes friended with the main class)?

Or to put it differently, how does inheritance apply to the friend keyword?

To expand: And if not, is there any way to inherit friendship?

I have followed Jon's suggestion to post up the design problem:

C++ class design questions


Friendship is not inherited in C++.

The standard says (ISO/IEC 14882:2003, section 11.4.8):

Friendship is neither inherited nor transitive.


You can create (static) protected methods in the parent that will allow you to do things like that.

#include <stdio.h>

class MyFriend
{
private:
    int m_member = 2;
    friend class Father;
};

class Father
{
protected:
    static int& getMyFriendMember(MyFriend& io_freind) { return io_freind.m_member; }
};

class Son : public Father
{
public:
    int doSomething(MyFriend& io_freind)
    {
        int friendMember = getMyFriendMember(io_freind);
        return friendMember;
    }
};

int main(){
    MyFriend AFriendOfFathers;
    Son aSonOfFathers;
    printf("%d\r\n", aSonOfFathers.doSomething(AFriendOfFathers));
    return 0;
}

This however bypasses encapsulation so you probably should take a second look at your design.


friend only applies to the class you explicitly make it friend and no other class.

http://www.parashift.com/c++-faq-lite/friends.html#faq-14.4


The answer is very simple: no, subclasses do not inherit friend associations. A friend can only access the private members of the class the association is declared in, not those of parents and/or children of that class. Although you might be access protected member of a superclass, but I'm not sure about that.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜