Overriden method not detected ?

Jonathan M Davis via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Fri Jun 3 05:41:39 PDT 2016


On Friday, June 03, 2016 12:03:29 chmike via Digitalmars-d-learn wrote:
> When trying to compile the following code I get a compilation
> error
>
> ----
> import std.stdio;
>
> class Info
> {
>      final string name() { return nameImpl(); }
>      protected abstract string nameImpl();
> }
>
> final class MyInfo : Info
> {
>      this() { assert(__ctfe); }
>      private __gshared info_ = new MyInfo; // Line 12
>
>      static string name() { return "MyInfo"; }
>      protected override string nameImpl() { return name(); }
> }
>
> void main()
> {
>      writeln("Hello world!");
> }
> ----
> source/app.d(12,31): Error: cannot create instance of abstract
> class MyInfo
> source/app.d(12,31):        function 'string nameImpl()' is not
> implemented
>
> If I move the info_ static variable declaration after the
> nameImpl method declaration, there is no error anymore.
>
> Is this normal ? What rule is in play here ? Or is this a
> compiler bug ?

It definitely looks like a compiler bug, though it wouldn't have surprised
me if the compiler considered it illegal to declare a static function in a
derived class where the base class has a final function with the same name.
Still, regardless of the legality of reusing the name like that, the error
message is pretty clearly wrong, and the order of declarations shouldn't
matter within a class unless you're doing something with static if.

On a side note, be warned that you almost certainly shouldn't be using
__gshared like this. It's intended for interacting with C code not for D
objects to be marked with D. As far as the type system is concerned,
__gshared isn't part of the type, and the variable will be treated as
thread-local by all of the code that uses it, which can result in really
nasty, subtle bugs when the compiler starts doing stuff like optimizations.
If you want to be sharing D objects across threads, you really should be
using shared so that the compiler knows that it's shared across threads and
will treat it that way.

- Jonathan M Davis



More information about the Digitalmars-d-learn mailing list