Bluethousandand2
Bluethousandand2

Reputation: 55

Dynamically create objects in c++?

Take a look at this code, it has a class that, when a new object is created, will give it a random number for 'lvl' between 1 and 100. After the class, I define some objects using class instances.

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    class newPokemon {
        public:
            int lvl;
            newPokemon() {
                lvl = (rand() % 100 + 1);
            };
            void getLevel() {
                cout << lvl << endl;
            };
    };

    newPokemon Gengar;
    newPokemon Ghastly;
    newPokemon ayylmao;
};

What I want to do next is allow the use to define new pokemon (objects) by asking them for a name. This means, however, I need to create objects dynamically. For example,

Program asks user for a name
Name is then saved as an object from the class newPokemon
Program can use that name to run other functions from the class, like getLevel.

How am I able to do this? I, of course, get that I can't do it like the hard coded ones, as I cannot reference user input as a variable name, but is there some way to do what I am asking by manipulating pointers or something?

Upvotes: 0

Views: 165

Answers (2)

anatolyg
anatolyg

Reputation: 28241

Use std::map to hold your objects according to their names:

std::map<std::string, newPokemon> world;

You must make sure that your objects get added to the map immediately after being created.

std::string name;
... // ask the user for a name
world[name] = newPokemon();
std::cout << "Your level is " << world[name].getLevel() << '\n';

Upvotes: 3

dcow
dcow

Reputation: 7975

You probably just want each Pokemon to have a name property (member variable/field). Just make a bunch of Pokemon with the name filled in.

Upvotes: 1

Related Questions