Hi, I'm working on a project to learn how to pass one function to another one. From everything I've read it seems like I have to create a pointer to the function I want to pass and use that but I'm having trouble, I am getting two errors:
Error 1:
error C2440: '=' : cannot convert from 'int' to 'void (__cdecl *)(int)'
Error 2:
error C2664: 'Car::saveData' : cannot convert parameter 1 from 'void (__cdecl *)(int)' to 'int'
Here is my code, any suggestions or help is greatly appreciated...
// The function we want to pass:
void ToBeCalled();
// The function that will invoke the above function:
void Invoker(void(*)());
int main()
{
Invoker(&ToBeCalled);
return(0);
}
void ToBeCalled() { /*...*/ }
void Invoker(void(*TargetFunc)(/*No parameters*/))
{
// Invoke the passed function...
if(TargetFunc)
TargetFunc();
}
Edit: I really should explain why you're receiving those errors.
The first error is informing you that the left-hand operand of the assignment operator cannot be converted to the same type as the right-hand operand of the assignment operator. In this case, int cannot be converted to a void; only vice-versa makes sense.
As for the second error: Your function pointer requires a function that returns void and takes a single integer as an argument. You're attempting to pass Car::saveData, which I'm assuming is a method, who's prototype doesn't qualify to be passed to the function pointer. Also, you should note that a function pointer to a method has a different prototype. More specifically, this:
well what I want to do is to be able to save the mpg data to a file. I was told the best way would but to pass the functions (at least that's how I understood it).
In that case, since you're using OOP, try using inheritance. If that's out of the question because you don't know it, I would use function pointers, like such: