0

Excuse me if this is a stupid question, but I can't get my head around the following piece of code:

struct myStruct
  {
    static void func1(const event, void* pthis)
    {
       myStruct& foo = *static_cast<myStruct*>(pthis);

       if(event.action != ...).... return;
       if(event.action == ...) foo.func2(); 
    }

    void func2()
    {}
  }

So... pthis is casted to a static pointer of type myStruct? Does this mean foo is of type 'reference to myStruct', and is equal to the value pointed to by pthis.

Essentially foo is pointing to myStruct, without access to instances of myStruct?

I really don't get it...

Forcetti
  • 486
  • 6
  • 13
  • `*static_cast` it does dereference after cast – billz Sep 02 '14 at 11:10
  • 1
    [What are the differences between a pointer variable and a reference variable in C++?](https://stackoverflow.com/questions/57483/what-are-the-differences-between-a-pointer-variable-and-a-reference-variable-in?rq=1) –  Sep 02 '14 at 11:14
  • Why not `func1()` just accepts a reference of `myStruct`? what's the purpose of this design...my head really can't get around that :( – Marson Mao Sep 02 '14 at 12:45

1 Answers1

4

So... pthis is casted to a static pointer of type myStruct?

A static_cast has nothing to do with static variables. It's explained in Regular cast vs. static_cast vs. dynamic_cast that static_cast can be used to reverse implicit conversions to void pointer.

Essentially foo is pointing to myStruct, without access to instances of myStruct?

No, foo is not "pointing" to anything. foo is a reference being bound to the object dereferenced by pThis. foo can call member methods just like (*pThis) can.

Community
  • 1
  • 1
  • So foo is a reference, used to call member functions of myStruct. And thanks to static_cast the void pointer pthis can be used as any type of pointer? – Forcetti Sep 02 '14 at 12:43