Using input to call a member function

I'm a moderate C++ programmer at best, but I have the need to insert whatever is entered as input to call a member function. for example... assume there's a class called default and an instance of the class called dft1 of that class, now I want to call whatever is entered as imput as the "name' of the member function.

void one(string input)
{newnum = oldnum + 1
return newnum;}

int main()
{
int oldnum, newnum
string input
}

cout << "Insert your old number:" << endl;
cin >> oldnum;

cout << "how many would you like to add?" << endl;
cin >> newnum; //user enters "one" here, the name of the member function.

dft1.newnum(oldnum)

If this can't be done, I need to know a way to automate calls of member functions without a ton of if statements.... aka

if (newnum == "one")
dft1.one();
make the function virtual.
You can use std::map to map names to pointers:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#include <iostream>
#include <map>
#include <string>

struct object_t
{
   void func_1()
   {
      std::cout << "func_1" << std::endl;
   }

   void func_2()
   {
      std::cout << "func_2" << std::endl;
   }
};

typedef void (object_t::*func_ptr_t)();

int main()
{
   object_t object;
   std::map<std::string, func_ptr_t> func_map;

   func_map["func_1"] = &object_t::func_1;
   func_map["func_2"] = &object_t::func_2;

   std::cout << "enter function name: ";
   std::string name;
   std::cin >> name;

   std::map<std::string, func_ptr_t>::iterator it = func_map.find(name);

   if(it != func_map.end())
   {
      func_ptr_t func_ptr = it->second;
      (object.*func_ptr)();
   }
   else
   {
      std::cout << "wrong function name!" << std::endl;
   }

   return 0;
}
I think you ought to rethink your design pattern here.
Also, I don't know, but you may find "select on a string" helpful (scroll down): http://www.cplusplus.com/forum/general/11460/#msg54095

Topic archived. No new replies allowed.