Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c++ member function pointer problem

I'm new to c++ . I want to know about object pointer and pointer to member function . I wrote a code which is following:

code :

#include <iostream>
using namespace std;
class golu
{
   int i;
public:
   void man()
   {
      cout<<"\ntry to learn \n";
   }
};
int main()
{
   golu m, *n;
   void golu:: *t =&golu::man(); //making pointer to member function

   n=&m;//confused is it object pointer
   n->*t();
}

but when i compile it it shows me two error which is following:

pcc.cpp: In function ‘int main()’:
pcc.cpp:15: error: cannot declare pointer to ‘void’ member
pcc.cpp:15: error: cannot call member function ‘void golu::man()’ without object
pcc.cpp:18: error: ‘t’ cannot be used as a function.

my question are following :

  1. What I'm doing wrong in this code ?
  2. How to make object pointer ?
  3. How to make pointer to member function of a class and how to use them ?

Please explain me these concept.

like image 350
Golu Avatar asked Jun 07 '11 08:06

Golu


2 Answers

A member function pointer has the following form:

R (C::*Name)(Args...)

Where R is the return type, C is the class type and Args... are any possible parameters to the function (or none).

With that knowledge, your pointer should look like this:

void (golu::*t)() = &golu::man;

Note the missing () after the member function. That would try to call the member function pointer you just got and thats not possible without an object.
Now, that gets much more readable with a simple typedef:

typedef void (golu::*golu_memfun)();
golu_memfun t = &golu::man;

Finally, you don't need a pointer to an object to use member functions, but you need parenthesis:

golu m;
typedef void (golu::*golu_memfun)();
golu_memfun t = &golu::man;
(m.*t)();

The parenthesis are important because the () operator (function call) has a higher priority (also called precedence) than the .* (and ->*) operator.

like image 77
Xeo Avatar answered Oct 24 '22 17:10

Xeo


Two errors corrected here:

int main()
{
   golu m, *n;
   void (golu::*t)() =&golu::man; 

   n=&m;
   (n->*t)();
}
  1. you want a pointer to function
  2. the priority of the operators is not the one you expected, I had to add parenthesis. n->*t(); is interpreted as (n->*(t())) while you want (n->*t)();
like image 29
AProgrammer Avatar answered Oct 24 '22 18:10

AProgrammer