Nyck
Nyck

Reputation: 184

C++ how to call a class by using an element of an array

I am creating a Pokémon Battle Simulator, and I want to know if I can call a class by using an element of an array.

#include <iostream>
#include <time.h>
#include <string>

using std::cout;
using std::endl;
using std::string;

string PokémonArray[] = { "Pikachu","Pidgey" };

class Pokémon {
public:
    string basic_attack;
    int basic_attack_dmg;

    string getBasicAttackName() { return basic_attack; }

Pokémon() { ; }
};

class Pikachu : public Pokémon {
public:
    Pikachu(){ basic_attack = "Whatever"; }
};

int main(){
int random_num;
string randEnemy;

srand(TIME(NULL));
random_num = rand() % 2; //Generates a random number between 0 and 1

randEnemy = PokémonArray[random_num]; //Sets randEnemy to be equal to the element 0 or 1 (generated above) of the array

(randEnemy) enemy; //Try to create the object 'enemy' calling a class using an element of the array

}

How can I call the class by using an element of an array that has the same name?

Upvotes: 1

Views: 175

Answers (3)

EmDroid
EmDroid

Reputation: 6046

You can (and should) store the Pokemon in the array directly, but it will not be so simple as the other answer specifies, as apparently the Pokemon instances are polymorphic. So what you need to store is a pointer to the Pokemon instance.

At the best a smart pointer (for automatic destruction). Depending on the use, it can be either:

std::vector<std::unique_ptr<Pokemon> > PokemonArray;

or

std::vector<std::shared_ptr<Pokemon> > PokemonArray;

(depending whether or not the pointer instance can be owned by multiple owners)

Or a simple array, but I generally prefer the std::vector.

Upvotes: 1

Armen Tsirunyan
Armen Tsirunyan

Reputation: 133112

To answer your question directly - yes you can, but you will need lots of if/else statements and you will have to use the polymorphic base.

Pokemon* pokemon = nullptr;
if(randEnemy == "Pikachu")
    pokemon = new Pikachu;
else if (randEnemy == "Raichu")
    pokemon = new Raichu;
else if...

This pattern is called "Factory method" or "virtual constructor".

Upvotes: 1

user2393256
user2393256

Reputation: 1150

You could store the Pokemon in your array.

Pokemon PokémonArray[152];

And then just call their function directly once you need them.

randEnemy = PokémonArray[random_num];
randEnemy.basicAttack();

Upvotes: 0

Related Questions