opEquals and the Non-Virtual Interface idiom

Justin Johansson procode at adam-dott-com.au
Mon Sep 28 12:31:53 PDT 2009


Andrei Alexandrescu Wrote:

> It turns out this is a great example for NVI. In D, we could and should
> do the following:
> 
> class Object {
>      // Implement this
>      private bool opEqualsImpl(Object rhs) {
>          return false;
>      }
>      // Use this
>      final bool opEquals(Object rhs) {
>          if (this is rhs) return true;
>          if (this is null || rhs is null) return false;
>          return opEqualsImpl(rhs) && rhs.opEqualsImpl(this);
>      }
> }

"I took advantage of the fact that in a final function this may be null without an access violation."

That "advantage" cannot be the general case?
Surely that statement is only true when the final function is in a base class, X, (and X can only be Object in D, right?)
for reason that the compiler can spot that the method is never overriden in ANY subclass of X (Object) , and therefore the method can be called directly rather than having to be dispatched through a VFT and consequently there is no VFT entry for that method/function.

Coming from C++ reasoning (maybe rules are subtlety different in D),
the thought experiment goes like this ...

class A {
  bool opEquals(Object rhs) {print( "Hello A"); return false;}
}

class B: A {
  final bool opEquals(Object rhs) {print( "Hello B"); return false;}
}

class C: A {
}

B b = new B();
b.opEquals(obj);

prints: Hello B

C c = new C();
c.opEquals(obj);

prints: Hello A

C c;
c.opEquals(obj);

prints: An error has occurred in this application.
Please contact the program vendor for an upgrade.
Send error report to Microsoft?
Yes? No (crashing out like this is an advertised feature of the language this program was developed in)?

Just conjecture.

-- Justin Johansson




More information about the Digitalmars-d mailing list