Non-Virtual Interfaces

Steven Schveighoffer schveiguy at yahoo.com
Fri Mar 4 10:48:23 PST 2011


On Fri, 04 Mar 2011 05:17:00 -0500, Aleksandar Ružičić  
<ruzicic.aleksandar at gmail.com> wrote:

> I'm trying to use NVI idiom but i keep getting errors from dmd.
>
> This is my setup:
>
> module test;
>
> import std.stdio;
>
> interface IBase {
> 	void foo();
> 	void bar();
> }
>
> interface IBar : IBase {
> 	final void bar() {
> 		writefln("IBar.bar()");
> 	}
> }
>
> class Foo : IBar {
>
> 	void foo() {
> 		writefln("Foo.foo()");
> 	}
> }
>
> void main() {
>
> 	Foo foo = new Foo();
> 	foo.foo();
> }
>
> When I try to compile it i get "test.d(16): Error: class test.Foo
> interface function IBar.bar isn't implemented"
>
> And if I try to define bar() in Foo i receive "test.d(22): Error:
> function test.Foo.bar cannot override final function
> IBar.test.IBar.bar"
> which is expected since IBar.bar() is final.
>
> So, am I missing some point about NVIs here or is it just not yet
> implemented in dmd?

The traditional explanation of NVI is that the final function is never  
virtual.  In your case, bar must be virtual at the IBase level, so it must  
go in the vtable.

I'm unsure whether this is intended to be a bug or a feature.

What you may want to consider is an abstract class instead of NVI, as long  
as you don't need multiple inheritance, it should be fine.

-Steve


More information about the Digitalmars-d-learn mailing list