Does a subclass inherit, the main class' friend associations (both the main class' own and 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
Inheritance and friendship in C++ In C++, the friendship is not inherited. It means that, if one parent class has some friend functions, then the child class will not get them as friend.
Inheritance and Friendship in C++ If a base class has a friend function, then the function doesn't become a friend of the derived class(es). For example, the following program prints an error because the show() which is a friend of base class A tries to access private data of derived class B.
In C++, inheritance is a process in which one object acquires all the properties and behaviors of its parent object automatically. In such way, you can reuse, extend or modify the attributes and behaviors which are defined in other class.
The protected members are inherited by the child classes and can access them as its own members. But we can't access these members using the reference of the parent class. We can access protected members only by using child class reference.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With