Pointer to member variable again

Koroskin Denis 2korden at gmail.com
Wed Jul 30 04:38:24 PDT 2008


On Wed, 30 Jul 2008 06:39:30 +0400, ws <wisiong at gmail.com> wrote:

> Simen Kjaeraas Wrote:
>
>> On Tue, 29 Jul 2008 07:33:51 +0200, ws <wisiong at gmail.com> wrote:
>>
>> > Maybe i should have written it this way:
>> >
>> > int function() fp;
>> > int delegate() dp;
>> > int *ptr;
>> > class Cls
>> > {
>> >   int k;
>> >   int foo()  { return k; }
>> > }
>> >
>> > void main()
>> > {
>> >   fp = &Cls.foo;
>> >   assert(fp() == 0);
>> >
>> >   Cls c = new Cls;
>> >   dp = &c.foo;
>> >   ptr = &c.k;
>> > 	
>> >   assert(is(typeof(ptr) == int*));
>> >   assert(is(typeof(fp) == int function()));
>> >   assert(is(typeof(dp) == int delegate()));
>> > }
>> >
>> > Notice fp can be used without an instance of Cls.
>> > What i need is actually a way to get the type of the class when i
>> > reference the variable k, without actually creating an instance of the
>> > class.
>> > Something like this:
>> >
>> > typedef GetClass!(Cls.k) classType;
>> > assert(is(typeof(classtype) == class) && is(typeof(classtype) ==  
>> Cls));
>> >
>> > Is there a way to do it?
>>
>> Have you tried calling fp in that example?
>>
>> --
>> Simen
>
> Sorry the fp has to be called after Cls is instanstiated. Fixed as below:
>  fp = &Cls.foo;
>  Cls c = new Cls;
>  assert(fp() == 0);  <-- after Cls instantiation.
>

No, that's wrong. Suppose you have two instances:

Cls first = new Cls();
first.k = 1;

Cls second = new Cls();
second.k = 2;

int result = fp();	

Question is what is the result of the fp() call?

Lets do some renaming:

class Human {
     char[] name;
     char[] getName() { return name; }
}

Human me = new Human();
me.name = "Denis"

Human you = new Human();
you.name = "Rui";

char[] name = Human.getName(); // what's the result?

char[] function() fp = &Human.getName();
char[] name2 = fp();

The answer is... none. The code is wrong. You can't access a property,  
which is different among class instances, like there is no such thing as  
common human name. Or age. Or anything else. There should be someone whose  
properties you are trying to determine - an object, class instance.

char[] name1 = me.getName(); // returns "Denis"
char[] name2 = you.getName(); // returns "Rui"


More information about the Digitalmars-d-learn mailing list