2

I've never used function pointers before and I'm having some trouble getting my code to work. This is what I have

TestClass.h:

class TestClass
{
    public:
        void function1();
        void function2();

        void function3(void (*funcPtr)(void))
        void function4();
};

TestClass.cpp

void TestClass::function1()
{
    //CODE
}

void TestClass::function2()
{
    //CODE
}

void TestClass::function3(void (*funcPtr)(void))
{
    //CODE
    funcPtr();
    //CODE
}

void TestClass::function4()
{
    function3(function1);
    function3(function2);
}

This give me the error

"nonstandard form for taking the address of a member function

I tried to add TestClass:: infront of the *funcPtr but that gives me even more errors

2
  • Non-static member functions aren't functions - you cannot call a member function. Instead, you have to invoke it on an object. Commented Oct 6, 2015 at 9:03
  • You want: void f(TestClass * obj, void (TestClass::* mf)()) { (obj->*mf)(); } and call it like f(this, &TestClass::function1). Commented Oct 6, 2015 at 9:04

2 Answers 2

7

With member function pointer, it should be something like:

void TestClass::function3(void (TestClass::*funcPtr)())
{
    //CODE
    (this->*funcPtr)();
    //CODE
}

void TestClass::function4();
{
    function3(&TestClass::function1);
    function3(&TestClass::function2);
}

With function pointer

class TestClass
{
    public:
        static void function1(); // static added
        static void function2(); // static added

        void function3(void (*funcPtr)(void))
        void function4();
};

void TestClass::function3(void (*funcPtr)())
{
    //CODE
    funcPtr();
    //CODE
}

void TestClass::function4();
{
    function3(&TestClass::function1);
    function3(&TestClass::function2);
}
Sign up to request clarification or add additional context in comments.

Comments

1

I suggest you to use std::bind and std::function, which provide a better readability and more checking for you

http://en.cppreference.com/w/cpp/utility/functional/bind

#include <functional>

void TestClass::function3( std::function<void (void)> funcPtr )
{
    //CODE
    funcPtr();
    //CODE
}

void TestClass::function4()
{
    function3( std::bind(&TestClass::function1, this) );
    function3( std::bind(&TestClass::function2, this) );
}

1 Comment

Currently working with embedded systems and don't have access to the newer versions of c++

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.