Re: [Vala] virtual / override



Srecko Howard wrote:
[...]
The virtual / override language options for methods.  I see that the
code will call the appropriate method regardless if you define the
method as virtual and override it.

Hello,

are you sure the correct method is invoked even when called through the
interface of a superclass? The precise reason for virtual method
dispatch is, that in a situation like this:

  class Base {
    public virtual void foo() { stdout.puts("Hello from Base!\n"); }
  }

  class Ext : Base {
    public override void foo() { stdout.puts("Hello from Ext!\n"); }
  }

  void main() {
    Base obj = new Ext();
    obj.foo();
  }

The result of calling obj.foo() will be that "Hello from Ext!\n" is
printed, while "Hello from Base!\n" would be printed if the method foo
wasn't virtual.

In my experiment with Vala 0.5.3, omitting the "virtual" in the above
example causes a compiler error when the "override" is encountered.
Omitting the "override" causes the probably wrong behaviour at the call
site of obj.foo(), that is the method Ext.foo does not override the
virtual method Base.foo in that case. And omitting both "virtual" and
"override" also causes "Hello from Base!\n" to be printed at the call
site, but in this case, that behaviour is correct.

[...]
The difference seems to be about 10 bytes of code if you don't specify
that the method is virtual before overriding it. So is there a speed
improvement by using explicit form?

Of course virtual method dispatch needs indirection through a table of
pointers, which uses some more space and is somewhat slower than a
normal function call.

[...]
Basically what is the recommended way (personally I don't like the C++
virtual methods stuff, Java based person).  Should it be required or
optional? 

Well, Java has the same kind of virtual methods as C++. The only
difference is that Java has no non-virtual instance methods at all which
makes the "virtual" keyword unnecessary.

Whether you make a method virtual or not depends on how you intend to
use it and whether you expect it to be overridden from outside your own
code or not (if you do, the method must be virtual). If your program
works correctly without virtual methods and you don't expect external
extensions, don't use virtual methods, since your code will be faster ;-)

[...]

cu,
Thomas



[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]