#include<iostream>
int foo(int a, bool(*n_ptr)(int a))
{
std::cout<<(*n_ptr)(10);
return a * a;
}
bool goo(int b)
{
return b*b;
}
int pass_char(int(*char_ptr)(int a))
{
std::cout<<"calling pass_char";
}
int main()
{
bool(*n_ptr)(int a); //make pointer to function
n_ptr = goo; //point to a function
std::cout<<foo(10, n_ptr); //dereference function
int(*char_ptr)(int a); //make pointer to another function<----difficulty here& onward
char_ptr = pass_char; // point it to function
//placeholder for function call
return 0;
}
.\src\main.cpp:29:10: error: invalid conversion from 'int (*)(int (*)(int))' to 'int (*)(int)' [-fpermissive]
char_ptr = pass_char; // point it to function
int(*char_ptr)(int a); Type of function is int(*)(int)...
trying to set it to:
int pass_char(int(*char_ptr)(int a))... type of this is int(*)(int(*)(int))
Notice the difference?
I'm not really sure what you're trying to accomplish though.... but here is some code that compiles, if you are after something specific, let me know:
#include <iostream>
#include <conio.h>
//typedef our functions, it makes everything below much simpler to follow!
typedefbool(*Func1)(int);
typedefint(*Func2)(int);
int foo(int a, Func1 func)
{
//Not sure why we return a bool value into an int??
return func(a);
}
bool goo(int b)
{
//Why are we returning a bool?
return b*b;
}
int pass_char(int a, Func2 func)
{
return func(a);
}
int goober(int b)
{
return b + b;
}
int main()
{
Func1 func1 = goo;
std::cout << foo(10, func1) << std::endl; //This simply prints the bool value?
Func2 char_func = goober;
std::cout << pass_char(5, char_func) << std::endl; //This actually prints the value 5+5
_getch();
return 0;
}
In answer to what I am trying to achieve here is a thought exercise. It has no other real utility than for learning more about passing function pointers through another function's parameter.
I cannot get char_ptr assigned to pass_char
I was able to get n_ptr assigned to goo
It seems this is where the problem lies. Thanks for the code, I am still studying it.
Notice how int(*char_ptr)(int) a); is defined as a function taking an integer, returning an integer. int()(int);
You are trying to assign your pass_char function to it, but look at it's definition:
int pass_char(int(*char_ptr)(int a))
It is NOT the same, it's taking a pointer to a function, which is fine if that's what you want, but you can't say int()(int) = int()(int(*)(int)), as the two types don't match.