In the case of A c = new C();
, it's going to call the first function it finds that correctly overrides the function declared in A
. Since C.P
doesn't override it, but hides it, the virtual tree traversal (polymorphic resolution) won't call the C.P
function, it'll instead call the lowest one in the inheritance tree, which is B.P
.
In the case of I ic = new C();
, it will happily call the direct interface implementation of P
, since it's not concerned with a polymorphic virtual call, so in that case it calls C.P
.
Note: it's key here that C
has I
directly in its inheritance declaration (i.e. looks like class C : B, I
instead of class C : B
) for this behavior. If it did not, the ic.P
call would again refer to the overridden inherited P
just like c.P
, and would also return 1.
You should see a warning that says the following, which helps give you a clue that something isn't done quite right:
'C.P
' hides inherited member 'B.P
'. To make the current member override that implementation, add the override
keyword. Otherwise add the new
keyword.