0

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?

4
  • any kind of growable collection like a vector. This will mean that each variable won't have it's own name but rather an index of some kind. Commented Jan 21, 2016 at 0:13
  • If I understand you right, you could use a std::map or std::unordered_map Commented Jan 21, 2016 at 0:14
  • We know; show us the actual code. What you want is to create a function that returns a Pokemon that accepts an argument of type string, which is for name. Commented Jan 21, 2016 at 0:16
  • It sounds like you just need to do dynamic allocation with the new operator: pokenmon_ptr = new newPokemon;. Commented Jan 21, 2016 at 0:30

2 Answers 2

3

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';
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.