aya tarek
aya tarek

Reputation: 13

pointer to function compilation error

I am trying to call the function using the pointer to function above but it keeps showing this error:expression preceding parentheses of apparent call must have (pointer-to-) function type. any help?

    #include<iostream>
using namespace std;
class a
{
public:
    a(){}
    int f(float m){cout<<"called.\n";return 1;}
};

int main()
{
    int (a::*ptr2)(float m) = &a::f;
    a *p ,obj;
    p = &obj;
    obj.*ptr2(.8);
    p->*ptr2(.5);
}

Upvotes: 1

Views: 138

Answers (1)

Alex Zywicki
Alex Zywicki

Reputation: 2313

You are simply missing some parenthesis around your function pointer calls.

#include<iostream>

class a
{
public:
    a(){}
    int f(float m) {
        std::cout<<"called."<<std::endl;
        return 1;
    }
};

int main()
{
    int (a::*ptr2)(float m) = &a::f;
    a *p ,obj;
    p = &obj;
    (obj.*ptr2)(.8); //note the difference
    (p->*ptr2)(.5);
}

It is in situations like this that std::invoke can be extremely handy: std::invoke Reference

Upvotes: 2

Related Questions