unimplemented abstract function compiles.

ag0aep6g anonymous at example.com
Sat Aug 11 23:30:14 UTC 2018


On 08/11/2018 10:55 PM, Eric wrote:
> Code below compiles while I would not expect it to compile.
> Is there a reason that this compiles?
> 
[...]
> 
> class I {
>    abstract void f();
> }
> 
> class C : I {
> }
> 
> unittest {
>    C c = cast(C) Object.factory("C");
>    c.f();
> }

Not a bug, as far as I see.

You don't get compile-time errors with Object.factory. It works at run 
time, on dynamic values (e.g., a class name entered on the command 
line). You're calling it with a constant string, but the compiler 
doesn't care about that. There's no special handling for that.

Object.factory returns `null` when it can't create the object. And it 
does that in your example, because of the abstract method (and because 
"C" is wrong; the name must be fully qualified). You're supposed to 
check for `null` before attempting to use the object.

If you want a compile-time check, don't use Object.factory. Use `new` 
instead:

     C c = new C; /* Error: cannot create instance of abstract class C */


More information about the Digitalmars-d-learn mailing list