Search code examples
c++classinheritancefriendfriend-function

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


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?


Solution

  • 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; }