0

I want to be able to use a member variable to hold the address a function to call

I got the error:

cannot convert 'void (TestClass::*)(bool)' to 'void (*)(bool)' in assignment

TestClass.cpp

#include "TestClass.h"

TestClass::TestClass()
{
    _myFctPtr = &setFired;
}

void TestClass::setFired(bool isFired)
{
    _fired = isFired;
}

void TestClass::updateValue()
{
    (_myFctPtr)(true);
}


bool TestClass::getFired()
{
    return _fired;
}

TestClass.h

#pragma once
class TestClass
{
    private:
        bool _fired = false;

    protected:
        void (*_myFctPtr)(bool);

    public:
        TestClass();
        void setFired(bool);
        void updateValue();
        bool getFired();
};
1

1 Answer 1

2

The error:

cannot convert 'void (TestClass::*)(bool)' to 'void (*)(bool)' in assignment

Is showing you that pointers to class member functions have a different type from regular function pointers. This is because, in addition to the regular function arguments and return type, these functions are differentiated by the object they are called on (i.e. their this), which must be provided when invoking them.

Specifically, for a pointer to a function on TestClass which accepts a bool argument as shown here, you need to to define your field as the type void (TestClass::*)(bool):

void (TestClass::*_myFctPtr)(bool);

You can call this like so, assuming you want to invoke the method on this:

((this).*(_myFctPtr))(true);

This article provides additional useful information and advice on better, cleaner ways to invoke pointers to member functions - e.g. using std::invoke for cleaner syntax than what I provided above - but this is the bare minimum to quickly solve your issue.

Sign up to request clarification or add additional context in comments.

2 Comments

Thank your for your quiock answer it helped me find a solution !
@CharlesPlante remember to mark a correct solution!

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.