Re: Dynamically allocated classes
Theo Richter <spammuelleimer@lorcoburger.de> writes:
[You are using some terms in a (IMHO) confusing way, so please accept
a little pickiness from my part.]
memory can be allocated dynamically at runtime using "new".
Indeed, with a call such as
::operator new(200)
For example, I could define a class "item" to hold information about
an item available in the stockroom of a company
class item {
/* information about the item and functions to access these data */
}
and use
item* pencil = new item;
to allocate memory for a pointer to item holding information about
say a pencil.
The new expression
new item
does *not* allocate memory for a pointer.
The definition
item* pencil;
already does that.
The new expression allocates memory for an object of class item. But
not only that, it also initializes it using class item's default
construtor.
I would now like to add an interface that the user can add new items
during the program execution until he has finished his job - so the
number is not fixed.
My first idea: I could use a vector of items (vector<item>) to hold
the classes and just append using push_back.
This vector won't hold classes; it will hold objects.
Are there other/better ways?
There are certainly other ways (you mention one further down); whether
there are better ways depends on what you mean by "good".
Can I dynamically create pointers with their names provided by the
user (e.g. the user types in "ruler" and this leads to an execution
like "item* ruler=new item").
No. Not exactly anyway.
First, again, this statement doesn't dynamically create a pointer. It
dynamically creates an object of type item.
Second, variable names are compile-time entities. In a program, you
can't create a variable whose name is a string input by the user to
that very program.
If class item has a constructor that takes a std::string (and a data
member holding the value passed to this constructor), you can do
something like:
std::string word;
if (std::cin >> word)
{
item *anotherItem = new item(word);
// do something with *anotherItem
}
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]