0

I am very kindergartener to C++. Hope someone can help me out with my problem.

Assume there is a function defined in one class.

void __foo__(int x, int y){
      //do something
}

In another class, there is a char pointer that holds the value of the function name.

static const char *func = "__foo__";

How do I call the function by using the "func" like func(0, 0)?

6
  • 2
    C++ doesn't have reflection, so you have to write the code to call the function based on the name yourself Commented May 21, 2021 at 17:56
  • 4
    On a side note, identifiers containing a double underscore are reserved. Commented May 21, 2021 at 17:58
  • Rather than suggest writing your own reflection code, I'm going to suggest not using strings to call functions in the first place. #include the class and call the function on an instance of it. And underscores like that are reserved. Use snake_case, camelCase or PascalCase (in my decreasing order of preference). Commented May 21, 2021 at 17:59
  • 2
    XY problem? Why are you trying to do that? Commented May 21, 2021 at 18:02
  • It's very important to clarify why you're trying to do that. Commented May 21, 2021 at 18:09

1 Answer 1

1

C++ doesn't have reflection, so you have to write the code to call the function based on the name yourself

void fall_function_based_on_name(const char* func_name, classWithMethod* self, lint x, int y) {
    if (strcmp(func_name, "__foo__")==0)
        self->__foo__(x, y);
    else 
        throw std::logic_error("method name not found");
}
Sign up to request clarification or add additional context in comments.

3 Comments

Aside: std::map and std::unordered_map can be useful here if you have a medium-large list of named functions or a use case that prizes ease of writing over performance.
Appreciate it so much for the help, @Mooing Duck. I guess the reason why it was given with the char pointer is that the foo__() will be given in the separate file during the runtime. Therefore, by calling _foo__() will produce "_foo was not declared in this scope" error in compile time.
@user3842642: Standard C++ doesn't have the concept of functions that don't exist at compile time, but most Operating Systems have ways of loading "dynamic libraries" at runtime (dlls on Windows). That's OS-specific though.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.