Function Pointer trouble.

Hi, i have a trouble with a function pointer using by this way (create an object) all will be allrigth. But, if i want to execute the function pointer in the constructor of the class "PointerFunction" i had a trouble and i don't understrand why i can't do it. Anyone can help?

//PointerFunction.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
#ifndef POINTERFUNCTION_H
#define POINTERFUNCTION_H

class PointerFunction
{
    public:
        PointerFunction();
        int product(int,int);
        int sum(int,int);
        int (PointerFunction::*ptr)(int,int);
};

#endif // POINTERFUNCTION_H


(Creating an object at the main) -- allrigth
//PointerFunction.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include "pointerfunction.h"
#include <iostream>
using namespace std;
PointerFunction::PointerFunction()
{

}

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

int main(){
    PointerFunction f;
    f.ptr = &PointerFunction::sum;
    cout << (f.*(f.ptr))(2,3);
    cout << "Choose: " << endl;
    return 0;
}


//PointerFunction.cpp -- without create an object, i had trouble. Here is the problem.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include "pointerfunction.h"
#include <iostream>
using namespace std;
PointerFunction::PointerFunction()
{
    ptr = &PointerFunction::product;
    cout << ((PointerFunction).*(ptr))(2,3) << endl;
     // i have try ((this).*(ptr))(2,3) << endl -- fail.
}

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

int main(){
    PointerFunction f;
    return 0;
}


Thx.
Last edited on
Try cout << (this->*(ptr))(2,3) << endl;
Thanks m4ster roshi.
Topic archived. No new replies allowed.