Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 896
Nikhil Avatar asked Jun 05 '12 17:06

Nikhil


People also ask

Can we call member function using this pointer?

You can use pointers to member functions in the same manner as pointers to functions. You can compare pointers to member functions, assign values to them, and use them to call member functions.

Which pointer is used in pointer to member function?

The pointer to member operators . * and ->* are used to bind a pointer to a member of a specific class object. Because the precedence of () (function call operator) is higher than . * and ->* , you must use parentheses to call the function pointed to by ptf .

How do you call a function from a pointer?

The call by pointer method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the passed argument.

What is the correct syntax for calling a member function?

Which is the correct syntax to call a member function using pointer? Explanation: The pointer should be mentioned followed by the arrow operator. Arrow operator is applicable only with the pointers. Then the function name should be mentioned that is to be called.


1 Answers

(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)();
like image 113
James McNellis Avatar answered Sep 21 '22 19:09

James McNellis