Reputation: 383
I am trying to create a command-line game in C++
. I am new to it and just started learning.
My game consists of a player class and a dragon class. The classes are declared in separate header files.
What I would like to know is, if there is a way to call a random function of a class after declaration.
Like
// ignore the includes
class foo{
public:
string name = "foo";
foo(string name){
this->name = name;
}
void func1(){
//some code
}
void func2(){
//some code
}
void func3(){
//some code
}
}
/////
//main.cpp
#include <iostream>
#include "foo.h"
int main(){
foo bar("hello");
//call a random function like func1, func2, func3;
return 0;
}
Upvotes: 1
Views: 274
Reputation: 126
I am a beginner myself and I am sure there are much easier/better solutions than mine.
You can try it with cases.
int random_val = rand();
int nr = random_val % 3;
switch (nr) {
case 0: bar.func1();
break;
case 1: bar.func2();
break;
case 2: bar.func3();
break;
default:
std::cout << "Default case" << std::endl;
}
Upvotes: 4
Reputation: 4061
You can make an array with the given functions and generate a random int as an index into the array:
void invoke_random_function(foo& bar)
{
//make an array of pointers to desired functions
using func_type = void(foo::*)();
constexpr func_type funcs[] = {
&foo::func1,
&foo::func2,
&foo::func3
};
//select a random function from array
auto random_index = (std::rand() % std::size(funcs)); //use better RNG than std::rand if necessary
auto random_func = funcs[random_index];
//invoke the selected function with the given instance of the class
(bar.*random_func)(); //funny notation to invoke member function pointers
}
Upvotes: 3