0

I have the following code

#include<iostream>
using namespace std;
class operate
{
    int x;
    int y;
public:
    operate(int _x, int _y):x(_x), y(_y)
    {}
    void add(const char* ch)
    {
        cout<<ch<<" "<<x+y;
    }
    void subtract(const char* ch)
    {
        cout<<ch<<" "<<x-y;
    }
    void multiply(const char* ch)
    {
        cout<<ch<<" "<<x*y;
    }
};
int main()
{
    void (operate::*fptr[3])(const char*);
    operate obj(2,3);
    fptr[0] = &(operate.add);              //problem
    fptr[1] = &(operate.multiply);         //problem
    fptr[2] = &(operate.subtract);         //problem
    (obj.*fptr[0])("adding");
    (obj.*fptr[1])("multiplying");
    (obj.*fptr[2])("subtracting");
}

It seems I am not assigning the member functions to function pointer array properly. How can I solve this. I'm using VS2010

2
  • Please decide whether there is a mistake or not before posting a question. If you decided there is a mistake, tell us what behaviour you expect and what behaviour actually occurred. Commented Jul 16, 2013 at 8:41
  • @Oswald There is a mistake and VS2010 compiler isn't showing proper error message. It shows where to put punctuations and upon including those, again it is a compiler error Commented Jul 16, 2013 at 8:44

2 Answers 2

4

The dot (member-of) operator is used for accessing members of an object. For classes and namespaces, you have to use the :: operator. Also, don't parenthesize, since & has lower precedence than :: and it's more readable like

fptr[0] = &operate::add;
Sign up to request clarification or add additional context in comments.

2 Comments

@H2CO3: Hi bro, want to have chat with you. Is it possible?
@NishithJainMR Hi. Here you are.
0

This should do the job

void testFP()
{
    typedef void (operate::*memFP)(const char*); 
    memFP fptr[3];

    fptr[0] = &operate::add;
    fptr[1] = &operate::multiply;
    fptr[2] = &operate::subtract;
    operate op(42, 42);

    (op.*(fptr[0]))("adding");
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.