Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does the virtual keyword, in actionscript, does?

I have found some code that uses the virtual keyword for functions, like:

package tryOut{
    public class Parent {

        public function Parent() {}

        public function foo():void{
            trace("Parent foo");
        }//foo

        public virtual function bar():void{
            trace("Parent virtual bar");
        }//bar      
    }//class
}//package

As far as I understand using the virtual keyword should modify the way overriding a method works, or the way using a child method would work, or something. But it seems it does nothing at all. Having the extention:

package tryOut {
    public class Child extends Parent {
        public function Child() {}

        public override function foo():void {
            trace("Child foo");
        }//foo

        public override function bar():void {
            trace("Child virtual bar");
        }//bar

    }//class
}//package

The following code prints:

var parent:Parent = new Parent();
var child:Child = new Child();

parent.foo(); //Parent foo
child.foo(); //Child foo
parent.bar(); //Parent virtual bar
child.bar(); //Child virtual bar

var childCast:Parent = child as Parent;

parent.foo(); //Parent foo
childCast.foo(); //Child foo
parent.bar(); //Parent virtual bar
childCast.bar(); //Child virtual bar

So both methods work the same regarding the override. Does the virtual keyword changes something I am missing?

like image 335
Maic López Sáenz Avatar asked Feb 12 '10 00:02

Maic López Sáenz


2 Answers

From the help documents (If you're using Flash, do a search for 'virtual'):

There are also several identifiers that are sometimes referred to as future reserved words. These identifiers are not reserved by ActionScript 3.0, though some of them may be treated as keywords by software that incorporates ActionScript 3.0. You might be able to use many of these identifiers in your code, but Adobe recommends that you do not use them because they may appear as keywords in a subsequent version of the language.

abstract boolean byte cast

char debugger double enum

export float goto intrinsic

long prototype short synchronized

throws to transient type

virtual volatile

So in AS3, virtual does absolutely nothing.

like image 155
Ponkadoodle Avatar answered Sep 18 '22 13:09

Ponkadoodle


So both methods work the same regarding the override.

What makes you think that? The tests you've shown aren't comparable.

childCast is typed as a Parent, yet you still end up calling the function in Child.

You don't check the same situation for the non-virtual method.

like image 34
Anon. Avatar answered Sep 20 '22 13:09

Anon.