I’m reading a book on C++. And I figured I should practice a little of what I know. So I created a class, and it contained a member in the form of classname * name[] which I would allocate later with new because I didn’t know the amount of space it would need. So when I tried to type name = new classname[capacity /* a variable passed in constructor */], it didn’t work. Now that I think of it, this makes sense. I referred to my book, and I realized that name is the same thing as &name[0]. This explains why my IDE said “expression must be a modifiable lvalue”. So now my question is, how can I declare an array on one line, and assign it with new on another line? I would also like to know why type * name[] is valid as a class member, but not outside of a class?
class MenuItem
{
public:
MenuItem(string description):itsDescription(description) {};
void setDescription(string newDescription);
string getDescription() const;
private:
string itsDescription;
};
void MenuItem::setDescription(string newDescription)
{
itsDescription = newDescription;
}
string MenuItem::getDescription() const
{
return itsDescription;
}
class Menu
{
public:
Menu(int capacity);
private:
MenuItem * items[];
};
Menu::Menu(int capacity)
{
items = new MenuItem("")[capacity];
}
Any help is much appreciated.
Unlike Java,
MenuItem* items[]is not a proper type, and is only allowed in three situations, and you aren’t using it for any of those situations. Judging by the rest of your question, I assume you want a dynamically sized array ofMenuItemitems. In that case, your member should simply beMenuItem* items;. Then you can allocate an array of that object no problem.As the comments (and downvoters?) say, the “best” solution is simply to use a
std::vector<MenuItem> itemsmember instead, and let it automagically take care of the allocation and deallocation for you.Educational but not really important:
The only times in C++ when you can have empty brackets
[]are:and
and