Why I can't use pointer to a function

There is an objects with field double (A :: *ptrToFunc)(); Object B has got A; Can’t use it in objects B

class Foo
{
public:
    
    double (Foo :: *ptrToFunc)();
    
private:
    double func1();
    double func2();
    
public:
    Foo() : ptrToFunc{ &Foo::func1 } {}
}

class B
{
public:
    Foo obj;
    double countVal()
    {
        return (obj.*ptrToFunc)();  // use of undeclared identifier ptrToFunc
        return (obj.ptrToFunc)();  // called object (..) not a function or function pointer
    }
}

int main()
{
    B obj_B;
    double var = obj_B.countVal();
    return 0;
}

Read this https://www.codeguru.com/cplusplus/c-tutorial-pointer-to-member-function/, but it doesn’t help me.

>Solution :

There are 2 problems with your code.

Problem 1

Foo obj(); is a member function declaration and not a data member declaration because of vexing parse(note the absence of "most"). That is, Foo obj(); declares a member function named obj with no parameter and return type Foo.

To solve this replace it with:

//-----vv--->use braces
Foo obj{};

Problem 2

The second problem is that the syntax return (obj.*ptrToFunc)(); is incorrect as obj.prrToFunc refers to the pointer and we still need to use that pointer on an object(as shown below).

To solve this 2nd problem replace its with:

(obj.*(obj.ptrToFunc))() // or same as (obj.*obj.ptrToFunc)() 

Working demo

Leave a Reply