So I'm trying to learn how to use function pointers (ie to pass the address of a function to another function to execute it - like a call back). I have it working when I use it as follows:
Classes.h:
#include <iostream>
using namespace std;
class Class1
{
public:
void callBack( string source, void (*myFunc) (string))
{
cout<<"About to do call back..."<<endl;
myFunc( source );
}
};
Classes.cpp:
#include "Classes.h"
void thisWorks(string works )
{
cout<<"THIS ONE WORKS"<<works<<endl;
}
int main()
{
Class1 c1;
c1.callBack( "TESTING", &thisWorks );
return 0;
}
./Classes
About to do call back...
THIS ONE WORKSTESTING
However, I would like to figure out how to get it to work where I don't have any 'standalone/global' functions, just classes:
Classes.h
#include <iostream>
using namespace std;
class Class1
{
public:
void callBack( string source, void (*myFunc) (string))
{
cout<<"About to do call back..."<<endl;
myFunc( source );
}
};
class Class2
{
public:
Class2( string myString)
{
Class1 class1;
class1.callBack( myString, &test );
}
void test( string whatever )
{
cout<<"Call back function called!"<<whatever<<endl;
}
};
Classes.cpp
#include "Classes.h"
int main()
{
Class2 class2("TESTING" );
return 0;
}
However, when I compile it, I get:
"Classes.h", line 18: Error: Formal argument myFunc of type void(*)(std::basic_string<char, std::char_traits<char>, std::allocator<char>>) in call to Class1::callBack(std::basic_string<char, std::char_traits<char>, std::allocator<char>>, void(*)(std::basic_string<char, std::char_traits<char>, std::allocator<char>>)) is being passed void(Class2::*)(std::basic_string<char, std::char_traits<char>, std::allocator<char>>).
Based on some googling, I'm pretty sure I have to create a typedef to void of my class, but I'm a bit confused. (Note I have a much larger example, the above is to try and illustrate just the problem).