I'm using a C++ code which is coded by someone else. I want to know what is happening in this line of code.
tplayer
is an array and OnTickContext
is a bool
variable.
tPlayers[i].OnTickContext = (void*)this;
I'm using a C++ code which is coded by someone else. I want to know what is happening in this line of code.
tplayer
is an array and OnTickContext
is a bool
variable.
tPlayers[i].OnTickContext = (void*)this;
This looks like the programmer did not know what he was doing, or wanted to look smarter than he was. This very snippet of code:
tPlayers[i].OnTickContext = (void*)this;
assuming that OnTickContext
is a bool
variable, is equivalent to this:
tPlayers[i].OnTickContext = true;
Why is that?
First we're casting this
pointer, which points to the object the method you are inspecting is called on, to void*
. Nothing too fancy here. The trick lies in assigning any pointer (including void*
) to a bool
variable. The convertion behaves as such - if the pointer was nullptr
, the variable will be set to false
. Otherwise, it will be set to true
.
Clearly we see that assigning a pointer to a bool
variable can either yield true
or false
, then why did I say that it's always true
in this context?
That's because of the nature of this
pointer. The this
pointer is a pointer to the object that you are calling a method on. You cannot call a method without an object. The this
pointer will never be nullptr
.
To summarise, neither the cast ((void*)
) or the assignment of the pointer is necessary at all. Some compilers may even warn you that the assignment will always yield a true
value.
The programmer made a class in which he made OnTickContest bool variable which should be in public section. Then, he made an array of that class and assigns the value of that bool variable to the address of the calling object(this keyword here points to). This means if variable array has address it will be 1(true) else 0(false).