[SOLVED] Inheritance issue

Hi,

I have 2 classes, A and B, B inherites from A.

class A{
 function Foo(){
  Debug.Log("call as A");
 }
}
class B extends class A{
 function Foo(){
  Debug.Log("call as B");
 }
}

Now, in an other part of my code, I declare an object as an instance of A, but I instanciate an instance of B.

var myObj:A = new B();
myObj.Foo();

The default behaviour is that the call of Foo method is made as a A object, since I declare it as an A instance. But I’d like that my call was the one of the most inherited type, here B.
To make it easy, I’d like to change my line

myObj.Foo();

To somethings that will print “call as B” and not “call as A”.

I have heard somethings about virtual declaration, but I’m not really sure, and even less in Unity JavaScript langage.

Thanks a lot

Re,

I’ve find the answer,
just declare the method as virtual in the parent declaration.

Change:

class A{ 
 function Foo(){ 
  Debug.Log("call as A"); 
 } 
} 
class B extends class A{ 
 function Foo(){ 
  Debug.Log("call as B"); 
 } 
}

to:

class A{ 
 virtual function Foo(){ 
  Debug.Log("call as A"); 
 } 
} 
class B extends class A{ 
 function Foo(){ 
  Debug.Log("call as B"); 
 } 
}

Bye :slight_smile: