[haXe] overloading parent with different type

Nicolas Cannasse ncannasse at motion-twin.com
Sun Apr 9 10:42:36 CEST 2006


> hi all
> 
> Nicolas,
> Related to my older post, about qooxdoo: i wrote some code that would
> create haxe interfaces out of qooxdoo classes, and i've encountered
> the same problem:  there's a lot of methods that override methods with
> the same name in the parent class. I'm not sure i understand why this
> is an error.
> For example, c++ has no problem with this code:
> 
> class A{
> 	int f(){return 0;}
> };
> 
> class B:public A{
> 	std::string f(){return "hi";}
> };
> 
> Could you please elaborate a bit?

I don't know any language that provide this kind of selection. That
means that in your case B::f fully overload A::f, so the A::f is no
longer accessible when you have a "B" instance.

In general, selection is performed on the number/types of parameters.
This can sometimes be tricky, especialy in presence of subtyping :

class B extends A {
}

function f( a : A, b : B ) {
}

function f( b : B, a : A ) {
}


f( new B(), new B() );

Which method to choose ?

In haXe, you have an additional contraint, that is that for each call,
the behavior should be the same whatever if you know or not the type of
the arguments. Also, since objects are prototype-based, you can only
have one method for a given name "f". That means that in order to
correctly support method overloading, you need to generate one "generic"
method that will do the runtime dispatching :


function f( x, y ) {
   if( Std.is(x,A) && Std.is(y,B) )
	this.f__1(x,y);
   else if( Std.is(x,B) && Std.is(y,A) )
        this.f__2(x,y);
   else
        throw new TypeError();

}

Of course when at compile time you know the arguments type, you can
select directly the method f__1 or f__2 and thus skip the dynamic
dispatching.

Nicolas




More information about the Haxe mailing list