A pointer for function

Hello, I am having problem with this code (CPP), i can`t understand why i cannot refer a pointer function. Anyone can help me and can say me the correct way?

//// Here is FunctionPointer.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef FUNCTIONPOINTER_H
#define FUNCTIONPOINTER_H

class FunctionPointer
{
public:
    int sum(int,int);
    int product(int,int);
    int (*pointer)(int,int); // this pointer will be refer sum or product.
    FunctionPointer();
};

#endif // FUNCTIONPOINTER_H


/// - Here is the functionpointer.cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include "functionpointer.h"
#include <iostream>
using namespace std;
FunctionPointer::FunctionPointer()
{

}

int FunctionPointer::product(int a,int b){
   return (a*b);
}
int FunctionPointer::sum(int a,int b){
    return (a+b);
}

int main(){
    FunctionPointer f;
    f.pointer = f.product;
    cout << f.pointer(2,3) << endl;
    return 0;
}


///
error (Gnu C++): argument of type `int(FunctionPointer::)(int,int)` does not match `int(*)(int,int);

Thanks.

You are trying to create a function pointer to a member function.
Read here for more on making pointers to member functions:
http://www.newty.de/fpt/

Hope this helps.
Turn this -> int (*pointer)(int,int); into this -> int (FunctionPointer::*pointer)(int,int);

Also, turn this -> f.pointer = f.product; into this -> f.pointer = &FunctionPointer::product;

Finally, turn this -> f.pointer(2,3) into this -> (f.*(f.pointer))(2,3)

That should do it ;)
Last edited on
Thanks guys this was very useful
Topic archived. No new replies allowed.