Search code examples
c++inheritancefriend

Can derived class use friend function of the basis class?


If I have some class Basis, and derived from it Derived, inside basis I have friend function

friend int operator!=(const Basis&, const Basis&)

Inside derived class I don't have such function So my question is if I have inside my main

If( derived1 != derived2 ) ...

why does it work? i don't have any constructor for casting for != thanks in advance If I write if ( derived != basis ) will it work?


Solution

  • The compiler is comparing them as objects of class Basis. Since you can always implicitly convert from a derived class to a base class, the compiler is able to pass them to the Basis overload of operator !=. Of course, this comparison can only use fields declared in Basis, so if you want the comparison to be more specific by using members of Derived, you'll have to define a separate operator != overload.

    The friendship declaration isn't relevant when it comes to calling operator !=; all it does is allow operator != to access private members declared in Basis.