Jump to content
  • Advertisement

Archived

This topic is now archived and is closed to further replies.

Phillk6751

classe objects with unknown names till runtime

This topic is 5966 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i would like to know how i could create a class object with name that is unknown at runtime and use it effectively. Like i have a class of name Person and in the code instead of constructing it as "Person Human1" i want it to be determined upon the name that the user inputs so if the user inputs "Phill" then i want it to construct the object as "Person Phill", and also how would i make my code accept an object with a name like that when the class object is used?] or is this not possible? and if not any ideas(i don''t like the idea of sorting through objects by using their member functions to figure out if i have the right object or not)?

Share this post


Link to post
Share on other sites
Advertisement
No, you can't. The variable names are a source code artifact, they do not exist in the executable (i.e. at run time). Nothing prevents you from having a std::string name field in your Person class though, and get it initialised by the constructor.


class Person
{
private:
std::string name;
public:
Person( const std::string& _name )
: name( _name )
{}
};
...
std::string name;
std::cin >> name;
Person Human1( name );
...


Edit:

If you want to address object by name, you could always stick them in a std::map. (This is a 'brief' exposé which uses improper techniques, and is just there to goad you into reading the documentation for std::map)


std::map persons;
// should use boost::shared_ptr instead of Person* but...

Person* newPerson = new Person( "Phil" );
persons.["Phil"] = newPerson;
// should use insert() instead, but...
...
std::cout << persons["Phil"].age() << std::endl;
// Disadvantage of operator[] : it will create an object
// if none is found (e.g. if there is a typo in the name)
// insert and find are better, but i'm too lazy to lookup
// the proper syntax.



[edited by - Fruny on April 17, 2002 2:07:01 PM]

Share this post


Link to post
Share on other sites

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!