implement vs override
Peter C
peterc at gmail.com
Sat Nov 1 06:41:57 UTC 2025
On Friday, 31 October 2025 at 23:36:57 UTC, Quirin Schroll wrote:
>
> ..
> You can implement an interface method by inheriting from a
> class that defines the method without the base class
> implementing the interface.
ok. that took me a while to get my head around ;-)
--------------------------------
interface IsomeInterface
{
void someMethod();
}
class Base
{
void someMethod() { } // virtual by default in D.
}
class Derived : Base, IsomeInterface
{
// Note: no mention of void someMethod() anywhere.
}
-------------------------------
ok. now we have the 'accidental implementation' problem.
The compiler really should produce an error message here, in
relation to Derived:
> Error: 'Base.someMethod' signature conflicts with
> 'IsomeInterface.someMethod' signature. Add an explicitly
> declared void someMethod() in Derived, to resolve this
> ambiquity.
Fortunately in D, 'override' is now required to override a base
class method.
So now, the programmer *must* do either of these things:
(1)
class Derived : Base, IsomeInterface
{
// NOTE: D doesn't have an 'implement' keyword for implementing
an interface method.
void someMethod() {} // implementing the interface contract here
}
(2)
class Derived : Base, IsomeInterface
{
override void someMethod() {} // overiding the virtual member
inherited from Base.
}
Either way, the compiler is now satisfied that you have resolved
the 'accidental implementation' problem.
I don't expect D to make a change here, but this is how I would
have expected a compiler to behave in any case.
I think the Carbon language may have resolved this.
More information about the Digitalmars-d
mailing list