Function name as parameter?
CheesyBeefy (80)
Dec 27, 2008 at 1:17am UTC
I want to do something like this, but I don't know how:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
// +------------------------------------+
// | Brad Summers, (c) Contrast Gaming |
// | testcode2.cpp |
// | Testing Things (Code) |
// +------------------------------------+
#include <iostream>
using namespace std;
void myOtherFunction() {
cout << endl << "And this is the result." ;
}
void myFunction(function otherFunction, char parameter[80]) {
cout << parameter;
otherFunction();
}
int main() {
myFunction(myOtherFunction, "I am calling a function with a function." );
cin.ignore(80,'\n' );
return 0;
}
Is this possible?
helios (10258)
Dec 27, 2008 at 2:22am UTC
Following your example,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <iostream>
using namespace std;
void myOtherFunction() {
cout << endl << "And this is the result." ;
}
void myFunction(void (*otherFunction)(), char parameter[80]) {
cout << parameter;
(*otherFunction)();
}
int main() {
myFunction(&myOtherFunction, "I am calling a function with a function." );
cin.ignore(80,'\n' );
return 0;
}
Last edited on Dec 27, 2008 at 2:41am UTC
CheesyBeefy (80)
Dec 28, 2008 at 2:48am UTC
Works great, but so I can understand it, what do the * and & symbols mean in C++?
helios (10258)
Dec 28, 2008 at 3:06am UTC
void (*otherFunction)()
This means "a pointer called 'otherFunction', to a function that takes no parameters and returns nothing".
&myOtherFunction
This means "the memory address of the function 'myOtherFunction'".
(*otherFunction)();
This means "dereference the pointer 'otherFunction' and call the function it points to".
Topic archived. No new replies allowed.