thenoGk
thenoGk

Reputation: 33

Accessing non static members inside static method via passed pointer

Not the actual code, but a representation:

I need to initiate a thread from one of my member functions and I do that this way:

return_val = pthread_create(&myThread, NULL, myStaticMethod, (void*)(this));

i) I pass this as an argument because static methods do not allow non-static members to be accessed, and since I have non-static methods and members to access inside the static method. Is this right? Or, are there any other alternatives?

myStaticMethod(void* args)    
{
    args->myPublicMethod(); //Is this legal and valid?

    args->myPrivateMember;   //Is this legal and valid?
}

I get an error saying void* is not a pointer to object type, and I think that args is to be typecast into an instance of type myClass.

But, how do I do that?

Upvotes: 0

Views: 693

Answers (1)

R Sahu
R Sahu

Reputation: 206727

args->myPublicMethod(); //Is this legal and valid?

No. That is neither legal nor valid. However, you can use:

reinterpret_cast<MyClass*>(args)->myPublicMethod();

You can access a private member function of a class from a static member function. So, you can access a private member of the class using:

reinterpret_cast<MyClass*>(args)->myPrivateMember;

Another SO question and its answers discuss the pros and cons of using static_cast and reinterpret_cast. Since you are using void* as the intermediate type, you can use either of them.

Upvotes: 1

Related Questions