implement vs override
Peter C
peterc at gmail.com
Mon Nov 3 08:02:06 UTC 2025
On Monday, 3 November 2025 at 07:26:24 UTC, Serg Gini wrote:
> On Sunday, 2 November 2025 at 23:13:08 UTC, Peter C wrote:
>> On Sunday, 2 November 2025 at 11:33:56 UTC, Dejan Lekic wrote:
>
> why do you think Base is considered as an implementation of the
> interface?
Actually I've confused myself (and likely others) because I
thought this code below actually compiled at one stage (with no
error) - turns out... it won't compile.
It will produce an error:
Error: class `myModule.Derived` interface function `void
someMethod()` is not implemented
In C#, the code below would actually compile just fine, because
in C#, a public method in a base class automatically satisfies an
interface method in a derived class if the signatures match.
In D, it seems the rule is a little different: A class that
claims to implement an interface must itself provide
implementations for all interface methods. Inherited methods from
a base class are not counted *unless* the compiler can directly
see that the derived class provides them (i.e. via an 'override'
of the base method).
Turns out I prefer the way D *prevents* this from compiling, and
actually requires that you 'override' the method in Derived. That
signals an explicit action by the programmer to deal with this
situation - whereas C# just blindly compiles it.
The only way to get the code below to compile in D, is to
'override' someMethod in Derived.
But...
.. what if I need to keep the semantics of the base class method
(or override for some reason), but also implement the semantics
of the interface contract?
In C# I can do both, by using an 'explicit interface declaration'
- which D does not have.
I won't spend more time on this, cause it's pretty rare scenario
in the work I do, but I've learnt something useful, so wasn't a
complete waste of time - for me anyway ;-)
btw. Would be interesting to know if anyone in the past has ever
suggested C# like explicit interface implementation for D, and
what the response was.
.................................
module myModule;
import std;
void main()
{
Derived d = new Derived();
d.someMethod();
}
interface Isomething
{
void someMethod();
}
class Base
{
void someMethod()
{
writeln("Hello from Base");
}
}
class Derived : Base, Isomething
{
}
.................................
More information about the Digitalmars-d
mailing list