Question
How to Use pointers to members to refer to nonstatic members of class objects?
Solution
// MemberFunc.cpp : Defines the entry point for the console application.
//
#include <iostream>
using namespace std;
class Fred {
public:
int f(int x, int y){ return x + y;}
int g(int x, int y){ return x - y;}
int h(int x, int y){ return x * y;}
int i(int x, int y){ return x / y;}
int val;
};
typedef int (Fred::*FredMemFn)(int x, int y);
typedef int Fred::*FredMemPtr;
int main()
{
Fred fred;
FredMemFn p[] = {
&Fred::f,
&Fred::g,
&Fred::h,
&Fred::I
};
for(int i = 0; i < sizeof(p) / sizeof(p[0]); ++i){
cout << (fred.*p[i])(10, 12) << endl;
}
FredMemPtr v = &Fred::val;
fred.*v = 10;
cout << fred.val << endl;
return 0;
}
Output
22
-2
120
0
10
Press any key to continue . . .