Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading