i'm looking to create something like this but i don't know how to pass a function to another function and i cant figure it out from anything online
void function(){
25 * var +21
}
class new {
int var = 20;
public:
int output;
void process(void a){
output = a;
}
};
int main(){
new n;
n.process(function);
cout << n.output << endl;
}
You're referring to the use of function pointers. Function pointer syntax can be ugly.
In C++, people usually prefer std::function objects, or polymorphism.
It would help if you posted code that was a bit more concrete, I'm not exactly sure what you're doing there. Your function() doesn't actually do anything. And "new" can't be the name of a class in C++ because it's a keyword. I would suggest just getting used to how functions work before you tackle function pointers.
// Example program
#include <iostream>
int function(int var){
return 25 * var + 21;
}
class my_class {
public:
int output;
my_class()
: output(0) {}
// process a function that takes in an int, and returns an int
void process(int (*func)(int)) {
output = func(var);
}private:
int var = 20;
};
int main() {
my_class n;
n.process(function);
std::cout << n.output << std::endl;
}
I understand how they work and I know new cannot be used as a name for a function I just couldn't think of another name if you would like a snippet of the code I'm working on to get a better idea of what I'm doing I would be happy to provide it
if anyone could give me an example for what im trying to do that would be great ive been looking at the tutorials online and dont really understand because there trying to do somthing completely different than me it seems.
#include <iostream>
usingnamespace std;
int square( int x ) { return x * x; } // Some example
int triple( int x ) { return 3 * x; } // functions of the
int subt10( int x ) { return x - 10; } // required form
class Thing
{
int var;
public:
Thing( int v ) { var = v; }
int getVar() { return var; }
void process( int (*f)(int) ) { var = f( var ); } // Either of these
// void process( int f(int) ) { var = f( var ); } // will work
};
int main()
{
Thing n( 2 ); cout << "Start : var = " << n.getVar() << endl;
n.process( triple ); cout << "Triple: var = " << n.getVar() << endl;
n.process( square ); cout << "Square: var = " << n.getVar() << endl;
n.process( subt10 ); cout << "Sub 10: var = " << n.getVar() << endl;
}
Start : var = 2
Triple: var = 6
Square: var = 36
Sub 10: var = 26
This is "pointers to functions". @Cubbi's list is much more comprehensive.