Are friend functions inherited? and why would a base class FRIEND function work on a derived class object?

ぐ巨炮叔叔 提交于 2020-01-16 05:26:27

问题


class baseClass {
public:
  friend int friendFuncReturn(baseClass &obj) { return obj.baseInt; }
  baseClass(int x) : baseInt(x) {}
private:
  int baseInt;
};

class derivedClass : public baseClass {
public:
  derivedClass(int x, int y) : baseClass(x), derivedInt(y) {}
private:
  int derivedInt;
};

in the function friend int friendFuncReturn(baseClass &obj) { return obj.baseInt; } I don't understand why would the friend function of the base class work for the derived class? should not passing derived class obj. instead of a base class obj. tconsidered as error? my question is why it works when i pass a derived class object to it?


回答1:


Are friend functions inherited?

No, friend functions are not inherited.

Why would a base class function work on a derived class object?

Because friend function is using the data members available in base class only. Not the data members of derived class. Since derived class is a type of base class So, friend function is working fine. But note that here derived class instance is sliced and having information available only for base class. friend function will report an error if you will try to access restricted members of derived class. e.g.

 int friendFuncReturn(baseClass &obj) { return ((derivedClass)obj).derivedInt; }



回答2:


No. You cannot inherited friend function in C++. It is strictly one-one relationship between two classes.

C++ Standard, section 11.4/8

Friendship is neither inherited nor transitive.



来源:https://stackoverflow.com/questions/47469715/are-friend-functions-inherited-and-why-would-a-base-class-friend-function-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!