Pointers to member functions

P

Protoman

Why doesn't this code work; it should:

class Obj
{
public:
void a(){cout << "A!" << endl;}
void b(){cout << "B!" << endl;}
void c(){cout << "C!" << endl;}
};

int main()
{
void (Obj::*pFn)();
Obj obj;
pFn=&Obj::a;
obj->*pFn();
pFn=&Obj::b;
obj->*pFn();
pFn=&Obj::c;
obj->*pFn();
system("PAUSE");
return 0;
}

Help? Thanks!!!!!
 
A

Alf P. Steinbach

* Protoman:
Why doesn't this code work; it should:

Protoman, you miserable old troll, /when/ are you going to read the FAQ
item on how to post?

Tell what you expect, and what actually happens.

Be precise, include the actual error message(s) by copying and pasting.

class Obj
{
public:
void a(){cout << "A!" << endl;}
void b(){cout << "B!" << endl;}
void c(){cout << "C!" << endl;}
};

OK, except for lack of indentation.

int main()
{
void (Obj::*pFn)();
Obj obj;
pFn=&Obj::a;
obj->*pFn();

'obj' is not a pointer, so '->' is not applicable ('.' is).

Also, you need parentheses.
 
M

Murali Krishna

* Protoman:
'obj' is not a pointer, so '->' is not applicable ('.' is).

Also, you need parentheses.

yes.. as the following code.

(obj.*pFn)();

-- Murali Krishna
 
P

Protoman

Murali said:
yes.. as the following code.

(obj.*pFn)();

-- Murali Krishna

I figured that one out a couple hours ago, but my DSL and phone lines
were being upgraded, so I couldn't post right away. Anyway, can't you
use pointers to member functions to call functions based on a string
arg?
 
L

Luke Meyers

Protoman said:
Anyway, can't you
use pointers to member functions to call functions based on a string
arg?

The number and type of the arguments of a member function are, of
course, irrelevant to whether you can call said member function via a
PMF. Are you asking whether you can somehow specify the name of the
function as a string, and derive a PMF therefrom? Unless you implement
it yourself, no, you cannot.

By "implement it yourself," I mean for example something like:

class Foo { void fun() {} };
typedef Foo::*() pmfFoo;
std::map<std::string, pmfFoo> lookupTable;
lookupTable["fun"] = &Foo::fun;
Foo f;
f.*lookupTable["fun"]();

I didn't compile this, so haven't found all the syntax errors, but you
get the idea.

Luke
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top