Nikhil
Nikhil

Reputation: 2318

function pointers in c++ : error: must use '.*' or '->*' to call pointer-to-member function in function

Code snippet is as follows. Not able to understand why I am getting this error.

void
SipObj::check_each_field()
{
  map <std::string, sip_field_getter>::iterator msg;
  string str;
  char name[20];
  bool res = false;
  sscanf(get_payload(), "%s %*s", name);
  LOGINFO(lc()) <<  "INVITE:" << name;
  str = name;
  msg = sip_field_map.find(str);
  if (msg != sip_field_map.end()) {
      sip_field_getter sip_field = msg->second;
      res = (this).*sip_field();
  }
}

 typedef bool (SipObj::*sip_field_getter)();
 static map <std::string, sip_field_getter> sip_field_map;

sip_field_getter is a place holder for function names

Upvotes: 20

Views: 18642

Answers (3)

James McNellis
James McNellis

Reputation: 355069

(this).*sip_field();

There are two problems with this expression:

  1. this is a pointer, so you must use ->* to call a member function via pointer on it.

  2. the function call (()) has higher precedence than the member-by-pointer operators (either .* or ->*), so you need parentheses to correctly group the expression.

The correct expression is:

(this->*sip_field)();

Upvotes: 39

Sarfaraz Nawaz
Sarfaraz Nawaz

Reputation: 361472

The correct syntax is this:

(this->*sip_field)();

Or if you want to use . instead of ->, then this:

((*this).*sip_field)();

I would prefer the former syntax.

Upvotes: 6

Viper Bailey
Viper Bailey

Reputation: 11997

It looks like you're calling a method pointer on a pointer, but you're calling it with the dot-star syntax. Try replacing

res = (this).*sip_field();

with

res = (this->*sip_field)();

Upvotes: 12

Related Questions