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)?

  • 2
    C++ doesn't have reflection, so you have to write the code to call the function based on the name yourself – Mooing Duck May 21 '21 at 17:56
  • 4
    On a side note, identifiers containing a double underscore are [reserved](https://en.cppreference.com/w/cpp/language/identifiers#In_declarations). – G.M. May 21 '21 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). –  May 21 '21 at 17:59
  • 2
    XY problem? Why are you trying to do that? – n. m. could be an AI May 21 '21 at 18:02
  • It's very important to clarify why you're trying to do that. – Aykhan Hagverdili May 21 '21 at 18:09
  • Thanks for all the answers. To answer why I am trying to do that, not that I try to do it but it was given by the assignment... I am not allowed to change anything outside the function where it should call the __foo__(). – user3842642 May 21 '21 at 18:22

1 Answers1

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");
}
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
Mooing Duck
  • 64,318
  • 19
  • 100
  • 158
  • 2
    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. – user4581301 May 21 '21 at 18:01
  • 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 May 21 '21 at 20:12
  • @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. – Mooing Duck May 21 '21 at 21:06