Method hiding

bearophile bearophileHUGS at lycos.com
Thu May 27 15:04:34 PDT 2010


Steven Schveighoffer:

> However, doing this may lead to further issues.  I think if you had a  
> class C that derived from B, calling B.foo(c) would result in an ambiguity  
> without a cast.

This is D code:

import std.c.stdio: puts;

class A {
    void foo(A a) { puts("A.foo"); }
}

class B : A {
    alias A.foo foo;
    void foo(B b) { puts("B.foo"); }
}

class C : B {}

void main() {
    A a = new A();
    B b = new B();
    C c = new C();
    b.foo(a); // Prints: A.foo
    b.foo(c); // Prints: B.foo
}

--------------------

A Java translation:


class A {
    void foo(A a) {
        System.out.println("A.foo");
    }
}

class B extends A {
    void foo(B b) {
        System.out.println("B.foo");
    }
}

class C extends B {
    public static void main(String[] args) {
        A a = new A();
        B b = new B();
        C c = new C();
        b.foo(a); // Prints: A.foo
        b.foo(c); // Prints: B.foo
    }
}


This time they both call the same methods, b.foo(c) calls B.foo(B), probably because C is closer to B than A in the hierarchy :-) In normal programs I'd like to avoid writing this code.

Bye,
bearophile


More information about the Digitalmars-d mailing list