// Penguin.h
#include <map>
#include <iostream>
class Penguin
{
typedef void (Penguin::*PenguinMet)();
std::map<int, PenguinMet> Methods;
void Move();
int p;
public:
Penguin();
void Walk();
};
Penguin::Penguin()
{
p = 0;
Methods[0] = &Penguin::Move;
}
void Penguin::Move()
{
std::cout << p << std::endl;
}
void Penguin::Walk()
{
this->*Methods[p];
*this.*Methods[p];
}
and this main()
// Main.cpp
#include "Penguin.h"
int main()
{
Penguin Tux;
Tux.Walk();
return 0;
}
But when I run it p is never printed.
What am I doing wrong?
Thanks
You’re not actually calling the function, you’re just looking at the value of the member function pointer as a void expression, which has no effect. Change
Penguin::Walkto this:That way you’re actually calling the method and passing in the proper arguments (zero arguments, in this case). Note that you need the extra parentheses, since function calls have higher precedence than the
->*and.*operators.