I recently started learning about classes and a question came to me.
I know how to create a class object. But how would you use user input to create a new object with the name they specified?
Printable View
I recently started learning about classes and a question came to me.
I know how to create a class object. But how would you use user input to create a new object with the name they specified?
The way is understand it you want after the program is compiled
the user to specify the name of a newly created object?
Impossible
Yes.
Probably the thing you want is to let the player create a new
profile in your game and that it creates a new object from the
player class with the name specified in the profile name right?
NO CAN DO!
Though what i do like to know is, if its possible to create an array
of objects, like 16 objects from the class player for 16 players
Thanks anyways. Figured it would be something neat to know. :(
It depends what you mean by "name".
An object can be created at runtime by using "new".
and the object could have a name, for example
char name[10]; as a data member.
But if you mean that you want the object to have a name like the way variables have names in a program, then the answer is no, but why would you want to anyway? Once a program is compiled the names are changed anyway and aren't included in the executable( for example Car car1; or int An_Integer; , after compilation these identifiers are all changed to information more useful to the computer )
taking things literally, you could always write yourself a runtime object system to suit your needs.
>But how would you use user input to create a new object with the name they specified?
You can't do this directly, for example, this won't work in C++:
However, using a lookup table of names and matching objects you can create the type of functionality with only a little more effort:Code:#include <iostream>
#include <string>
class test
{
public:
test()
{
std::cout<<"A new test is born!"<<std::endl;
}
};
int main()
{
std::string s;
std::cout<<"Enter a name: "<<std::flush;
std::getline ( std::cin, s );
test s;
}
-PreludeCode:#include <iostream>
#include <string>
#include <map>
class test
{
public:
test ( std::string& name )
{
std::cout<<"A new "<< name <<" is born!"<<std::endl;
}
};
int main()
{
std::string s;
std::map<std::string, test*> lookup;
std::cout<<"Enter a name: "<<std::flush;
std::getline ( std::cin, s );
lookup[s] = new test ( s );
delete lookup[s];
}
You can use a linked list or vector or some other container without a fixed size. Then if the user wants to create a new object you can add it to the container, although you won't be able to name it... unless you make one of the private variables it's name.