Calling members of null pointers-to-struct

Tor Myklebust tmyklebu at csclub.uwaterloo.ca
Sun May 6 14:06:57 PDT 2007


Why is this illegal in D?  As I understand it (from discussion with 
GregorR on IRC), methods of a D struct are not virtual --- the following 
program cannot use vtables as an excuse for its AssertError.


struct foo {
  int doit(int x) { return 42; }
}
void main() {
  foo *bar;  bar.doit(9);
}


Neither does the following slightly less trivial code (note that null 
pointers passed as the 'this' argument aren't dereferenced by struct 
list's methods):


struct list {
  list *next;
  int data;

  static list *make(list *foo, int bar) {
    list *x = new list();
    x.next = foo; x.data = bar;
    return x;
  }

  list *put(int k) {
    return make(this, k);
  }

  bool has(int k) {
    if (this == null) return false;
    return data == k || next.has(k);
  }
}

void main() {
  list *foo;
  foo = foo.put(42);
  foo = foo.put(17);
  foo = foo.put(31345);
  assert(foo.has(42));
  assert(foo.has(17));
  assert(foo.has(31345));
  assert(!foo.has(24));
}


(Except for one minor detail about foo not being initialised to null by 
default, this is perfectly good C++ code; calling a nonvirtual method of 
a null pointer-to-struct simply results in the 'this' parameter coming 
out to be null.  So, like, why doesn't D do the same?)


Tor Myklebust



More information about the Digitalmars-d mailing list