class - Dynamically create objects in c++? -


take @ code, has class that, when new object created, give random number 'lvl' between 1 , 100. after class, define 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 want next allow use define new pokemon (objects) asking them name. means, however, need create objects dynamically. example,

program asks user name
name saved object class newpokemon
program can use name run other functions class, getlevel.

how able this? i, of course, can't hard coded ones, cannot reference user input variable name, there way asking manipulating pointers or something?

use std::map hold objects according names:

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

you must make sure objects added map after being created.

std::string name; ... // ask user name world[name] = newpokemon(); std::cout << "your level " << world[name].getlevel() << '\n'; 

Comments

Popular posts from this blog

android - Why am I getting the message 'Youractivity.java is not an activity subclass or alias' -

python - How do I create a list index that loops through integers in another list -

c# - “System.Security.Cryptography.CryptographicException: Keyset does not exist” when reading private key from remote machine -