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

user8185371 picture user8185371 · Nov 24, 2017 · Viewed 7.5k times · Source
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?

Answer

msc picture msc · Nov 24, 2017

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.