reimplementing an interface in a derived class

Ali Çehreli acehreli at
Fri Jan 4 21:08:24 UTC 2019

On 01/04/2019 12:46 AM, Alex wrote:
 > On Friday, 4 January 2019 at 07:37:43 UTC, bauss wrote:
 >> No, because you OVERRIDE A's foo().
 >> A does not exist. A is B and when you cast B to A you just tell the
 >> compiler that the reference should only have A's signature available.
 >> You're not assigning B to A.
 > Let's assume this is right. How to force a B object to behave like an A
 > object?

Not possible by default. However, a B object is already behaving like an 
A object because e.g. it overrides the foo() member function.

 > I thought casting is a possible approach...

In this case, casting is using the B object through it's A interface. 
The overridden behavior does not change. (Actually, that is possible in 
languages that support multiple inheritance through multiple virtual 
function pointer tables (vtbl) but D does not support that.)

Although I'm getting into implementation details here, I think it helps 
with understanding the semantics. There is only one vtbl per class 
object in D and the function entries are all filled in during 
construction. So, a B object's 'foo' slot in that table is filled with So, such an object can foo() only as a B.

If there is such a need and B can indeed support behaving like an A, it 
can do so itself by calling, not through vtbl, but directly:

class B : A {
   override void foo() {;  // Calling directly

By the way, do you have a use case in mind? Perhaps there are other ways 
to achieve that.


More information about the Digitalmars-d-learn mailing list