unimplemented abstract function compiles.

ag0aep6g anonymous at example.com
Sun Aug 12 18:15:33 UTC 2018


On 08/12/2018 07:29 PM, Eric wrote:
> I thought it would work the same way as an interface (which must be 
> implemented by the direct sub class, otherwise compile error).

 From the spec text [1], I'd also expect an error. It says: "An abstract 
member function must be overridden by a derived class." And later: 
"Classes become abstract if any of its virtual member functions are 
*declared* abstract or if they are defined within an abstract attribute" 
(emphasis mine).

So, arguably, DMD shouldn't accept your `C` class as abstract. It's not 
marked as abstract itself, and it doesn't have a declaration of an 
abstract method either.

But in cases like this it's more likely that the spec will be changed to 
reflect what DMD does than DMD getting changed to break existing code.

> But apparently it's possible to implement an abstract function anywhere 
> in the class hierarchy. That makes it, in this case, impossible to check 
> during compile time.

You can check it at compile time. The compiler just doesn't do it for 
you proactively. `C` is an abstract class, just like `I` is, and there's 
a trait for that [2]:

     static assert(!__traits(isAbstractClass, C));

For nicer syntax, there's also a wrapper around it in std.traits [3]:

     import std.traits: isAbstractClass;
     static assert(!isAbstractClass!C);

If you want to make sure that your class isn't accidentally abstract, 
you can add an assert like that.


[1] https://dlang.org/spec/attribute.html#abstract
[2] https://dlang.org/spec/traits.html#isAbstractClass
[3] https://dlang.org/phobos/std_traits.html#isAbstractClass


More information about the Digitalmars-d-learn mailing list