0

I have a simple class that has a pointer to a function. The constructor points it to the function "morning()" and I get the error message when compiling:

error: cannot convert ‘Test::morning’ from type ‘void (Test::)()’ to type ‘Test::function {aka void (*)()}’
     Test() {assignPtr = morning;}

The code does compile when the "morning()" and the typedef are declared outside the function and I can't figure out how to make it work within the current class.

#include <iostream>
#include <string>

class Test {
  public:
    Test() {assignPtr = morning;}
    void say(std::string a) {name = a; assignPtr();};
  private:
    typedef void(*function)();
    void morning() {std::cout << "Good morning, " << name << std::endl;}
    void night() {};
    function assignPtr;
    std::string name;
};

int main() {
    Test a;
    a.say("Miguel");
}
msaitz
  • 35
  • 2
  • 7

2 Answers2

3

A pointer to member function is not a regular function pointer; the class is part of the type and you need to specify which object you want to call it with.

You need to use the correct type

typedef void(Test::*function)();

and then adjust the syntax both when creating the pointer and when calling it.

Test() {assignPtr = &Test::morning;} // Get pointer-to-member
void say(std::string a) {name = a; (this->*assignPtr)();};  // Use pointer-to-member
molbdnilo
  • 64,751
  • 3
  • 43
  • 82
0

Function pointers and pointers to member functions are NOT the same thing. That's what you're compiler is telling you. The types do not match. Your target is defined as void(*)() and you're trying to hand it void(Test::*)(). They don't even have the same calling semantics. The latter has a blind Test*const this parameter.

Change the type of function or give it a regular function to call.

Hint: any time your compiler errors out with a complaint of not being able to convert this to that...your types don't match.

Edward Strange
  • 40,307
  • 7
  • 73
  • 125