Weird Inheritance error
Monkey Forums/Monkey Programming/Weird Inheritance error
| ||
Iīm getting this error <quote> Unable to find overload for new(Int,Int,Int). </quote> When trying to create an object from child class... see an example: Class TActor extends Object Method New() end Method New(a:int, b:int = 0, c:int = 0) End Method OnOutsideRoom() End End Class Fire extends TActor Method OnOutsideRoom() PleaseDestroyMe() End End Function Main:int() Local in:Fire = new Fire(TActor.TYPE_ELLIPSE, 5, 5) //error here! End Why ? This is just an example to illustrate the problem, the real class is bigger and tested, just now when I tryed to extend it I got this error. Do I need to recreate the constructor ? Isenīt it inherited from its father? Thanks! |
| ||
It is not inherited as you'd think, but you will need to call each overload you want the child to expose from within the child class. You need to add Super.New() as the first line to each of the overloads in the child class matching the parent class. This will instantiate the base class's overloaded constructors as expected. Here's an updated example: |
| ||
So, constructors are NOT inherited from base class like other methods? It Means that all derivate class needs to create a constructor just to call father's one? |
| ||
Yes. It seems strange, I know, but this is the only way I've been able to get a child class to instantiate using the parent constructor. |
| ||
If I'm not wrong, New() is called from inheritance order, and overloads have to be declared on each class:Function Main() New MyClass3 End Class MyClass1 Method New() Print "MyClass1 New" End End Class MyClass2 Extends MyClass1 Method New() Print "MyClass2 New" End End Class MyClass3 Extends MyClass2 Method New() Print "MyClass3 New" End End This outputs: MyClass1 New MyClass2 New MyClass3 New So all important initialization code that needs to be inherited, should be placed on the parameterless New methods. Then overloads for this method should be defined in a per-class basis. Any class can add any number of overloads here at any point of the inheritance tree. |