related to function pointer

Hi I have just written a small code to understand function pointer.
bellow is the code in ms visual studio

#include "stdafx.h"
#include <iostream>
#include "conio.h"

using namespace std;

class Data
{
private:
int Ix;
public:
int setData(int Ivalue)
{
Ix=Ivalue;
return Ix;
}
};

int main()
{
Data MyData;
int (Data::*fnptr)(int)=&Data::setData;
int i=(MyData.*fnptr)(10);
cout<<i;
getche();
return 0;
}

plz help me to pass this function pointer to other function for some manipulation.
for Example
check(10,(MyData.*fnptr)(10))
for checking both values are same or not.
(MyData.*fnptr)(10) is not a function pointer. fnptr is. (MyData.*fnptr)(10) is just the value returned by the function fnptr points to.
Also, when you deal with function pointers, you should typedef them. It all becomes clear then.
bool check(int i, int (MyData::*_mem_fun_ptr)(int) );
closed account (1vRz3TCk)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#include <iostream>

using namespace std;

#define CALL_MEMBER_FN(object,ptrToMember)  ((object).*(ptrToMember))

class Data
{
private:
    int Ix;
public:
    int setData(int Ivalue)
    {
        Ix=Ivalue;
        return Ix;
    }
};

typedef int(Data::*data_fnptr)(int x); //Much easier if you typedef it

void userCode(data_fnptr p)
{ 
     //... 
}

int main()
{
    Data MyData;

    data_fnptr ptr = &Data::setData;

    int i= CALL_MEMBER_FN(MyData,ptr)(10);

    userCode(ptr);

    cout<<i;
    return 0;
}


P.S. It is a pointer-to-member-function
Topic archived. No new replies allowed.