Reputation: 13886
I'm delving into the topic of non-static member function pointers, and I find the syntax most disturbing. These pointers are interesting because you can do:
struct MyStruct
{
void nonStaticMembFunc1(){};
void nonStaticMembFunc2()
{
void (MyStruct::*funcPtr)() = &nonStaticMembFunc1; // Declare local pointer
(this->*funcPtr)(); // Use it through this instance
}
};
So if it's the case that you can always (as far as I know) drop the use of the "this" keyword, I tried to drop it in this case, with the following attempts:
(this->*nonStaticFuncPtr)(); // Normal use, works
(->*function1)(); // Trying to drop "this" keyword
(*function1)(); // Trying to drop the arrow, this seemed to make sense
(.*function1)(); // Trying the other way
Trying this made me confused about what scope you're in when in a nonstatic member function. If you can drop the keyword then you're already in its scope (if that's the right term), like when you can drop the use of the scope resolution :: operator if you don't need it. But I'm probably completely wrong about this.
Upvotes: 0
Views: 213
Reputation: 1
The answer is you can't:
struct MyStruct
{
void nonStaticMembFunc1(){};
void nonStaticMembFunc2()
{
void (MyStruct::*funcPtr)() = &MyStruct::nonStaticMembFunc1; // Declare local pointer
(*funcPtr)(); // See error message below
}
};
main.cpp: In member function 'void MyStruct::nonStaticMembFunc2()':
main.cpp:9:12: error: invalid use of unary '*' on pointer to member
(*funcPtr)(); // Use it through this instance
^~~~~~~
It's a member function pointer call. This appears separated from the current instances context, hence this
isn't implicit there.
Upvotes: 1