0

Sorry I'm totally new to C++ just started this semester. I have a question though. I know javascript some what well and I love how loose it is as a programming language. (It's both a good and a bad thing.) But there is one thing you can do in javascript that I'm not sure if you can do in c++.

I want to call some functions from an array of functions here is a link of that done in javascript. Javascript Array of Functions. My idea is to write a for loop that will go through functions in the order I want. (from first to last.) If there is an alternative to this I will be fine with that. I could even name the functions with a number after them like function1 for example if that might help. I'm not sure if this is possible, but any help or anything would be awesome thanks.

Community
  • 1
  • 1
John
  • 7,114
  • 2
  • 37
  • 57

2 Answers2

3

Do you talk about "function pointer"?

void f1() { .. }
void f2() { .. }
void f3() { .. }

typedef void (*pf)();

pf arf[3] = { f1, f2, f3 };

arf[0]();
ikh
  • 10,119
  • 1
  • 31
  • 70
2

If you don't want to use the function pointer

struct parent
{
   virtual void f();
}

struct child1 : parent
{
  void f(){};
}

struct child2 : parent
{
  void f(){};
}

struct child3 : parent
{
  void f(){};
}

.
.
.

struct childn : parent
{
  void f(){};
}


parent array = {child1,child2,child3,.....,childn};

array[n].f();

each child classes will contain different implementations of f(), so you can 

create an array of child structs and invoke the methods through the for loop. 
Varo
  • 831
  • 1
  • 7
  • 16