using CCSprite with setUserData

using CCSprite with setUserData
0.0 0



I try to use the foloowing code:

CCSprite *mole = (CCSprite *)sender;

But it’s not compile, but if I use:

CCSprite *mole = (CCSprite *)sender;

the code can pass by compiler.

What I doing wrong?


setUserData can accept only pointers, not boolean values. You can work around this by passing 1 or 0 instead of true and false (they do not point to anything but can be at least casted to void*).


This is very strange for me, the way that pointers work.

But I follow your advice and try the following code:

CCSprite *mole = (CCSprite *)sender;    
mole->setUserData((void *) 1);

and create an if

if (mole->getUserData() == (void *)0) continue;

I don’t believe, but work’s perfectly.



It works because pointers keep the address of pointed object in memory, which is actually a number. This is why you can convert numbers to pointers. You can safely pass any numbers this way but you can’t try access objects through such pointers because they don’t actually point to existing object (there’s no object at address 0 and 1). The numeric value of boolean false in C++ is 0, so it can be implicitly converted, but numeric value of true is undefined (it is 1 usually but not standartized) this is why your initial code doesn’t compile.


I understand ‘redaur redaur’, thanks for the detailed explanation for pointers in C++, this way I can understand better what happens.