parveen1981's blog

By parveen1981, history, 3 years ago, In English

Hello guys, I wanted to ask if there is any way such that I can pass a function to the constructor of the class and then store it as some variable so that I can execute it later.

Thanks in advance.

  • Vote: I like it
  • -3
  • Vote: I do not like it

»
3 years ago, # |
  Vote: I like it +17 Vote: I do not like it

Does this help?

code
»
3 years ago, # |
Rev. 3   Vote: I like it +5 Vote: I do not like it

Hi parveen. Hope this helps.

class functionsetter {

public:

int (*function_name)(int ,int);
functionsetter(int (*f1)(int,int)):function_name(f1)
{

}

};

int add(int x,int y) { return x+y; }

int main() {

functionsetter f1(add); int x = f1.function_name(3,5); cout<<x<<"\n"; }

Read this https://www.guru99.com/c-function-pointers.html

  • »
    »
    3 years ago, # ^ |
    Rev. 2   Vote: I like it +5 Vote: I do not like it

    Thanks for commenting. But I decided to use alpenglow method (I might use this too). Thanks. :)