views:

91

answers:

3

Hello, 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?

+1  A: 

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.

Nick Meyer
@Nick Meyer: if I write if( derived != basis ) will it work?
Chan
@Chan, yes, any combination of objects of type `Basis` or a derived class could be compared with your `operator !=` overload, with the caveat that the overload only uses the parts inherited from `Basis`. This is a consequence of the basic OO 'is-a' inheritance relationship. (http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming))
Nick Meyer
The best thanks a lot
Chan
A: 

It sounds like your friend function only compares the Basis parts of Derived. So, it works after a fashion, but ignores any data in Derived.

Pontus Gagge
A: 

Because your Derived class inherits everything that your Basis class has, which in this case is an operator overload for !=, your Derived objects (derived1 and derived2) also have them defined.

danyim