Thread overview
Initializing a delegate member
Dec 09, 2004
Lionello Lunesu
Dec 09, 2004
Russ Lewis
Dec 10, 2004
Lionello Lunesu
December 09, 2004
Am I missing something... again?

import std.c.stdio;

class compiles {
 this() { _putc = &putc_ascii; }
 void delegate(int) _putc;
 void putc_ascii(int c) { putchar(c); }
};

class does_not_compile {
 void delegate(int) _putc = &putc_ascii;
 void putc_ascii(int c) { putchar(c); }
};

int main( char[][]arg )
{
 // keep linker happy
 return 0;
}

-- 
L.

-- Get the root certificate at https://www.cacert.org/


December 09, 2004
Lionello Lunesu wrote:
> Am I missing something... again?
> 
> import std.c.stdio;
> 
> class compiles {
>  this() { _putc = &putc_ascii; }
>  void delegate(int) _putc;
>  void putc_ascii(int c) { putchar(c); }
> };
> 
> class does_not_compile {
>  void delegate(int) _putc = &putc_ascii;
>  void putc_ascii(int c) { putchar(c); }
> };
> 
> int main( char[][]arg )
> {
>  // keep linker happy
>  return 0;
> }

The thing that you have to remember is that a delegate actually has 2 pointers embedded in it: a function pointer, and a pointer to the object.  Thus, if you create 2 copies of the class "compiles", they will have different "_putc" members.

Since the value of the delegate varies from object to object, you can't initialize it statically.

December 10, 2004
Hi..

> The thing that you have to remember is that a delegate actually has 2 pointers embedded in it: a function pointer, and a pointer to the object. Thus, if you create 2 copies of the class "compiles", they will have different "_putc" members.

Yes, I missed that. However, the _putc is the same for both (same code for both), but the 'parameter' (==this) is different for both instances.

> Since the value of the delegate varies from object to object, you can't initialize it statically.

Yes, makes sense. I kind of figured that writing "class t { int a=0; };" would add "a=0;" to a generated constructor and that anything that's valid in a constructor could be written using the same syntax, but now I know that only 'statically evaluatable statements' (:-S) can be written liked that.

Thanks for the reply..

Lionello.