So, i have defined a father class of grocery items that have the attributes of the items such as price name and quantity. I was also asked to make a subclass for each category of groceries, such as dairy, cereal and such. I need to make a program that lets a the user populate a list (i think a vector would be the best choice) after the list is populated the user has to be able to change the quantity of each item.
I researched and since they are all different classes and dont all have the same attributes im going to need to use the pointer to point to that class then push it back, right? but im having a hard time coming up with the code.
i figured for the user end it will first ask u if u want to add an item. then what kind and then ask u to type in all the attributes. but im suppose to have one add function for all the classes.
so i fiured it would be something for the dairy i set the pointer to the dairty and then push back (new.dairy)?
It sounds like you are much closer than you think.
STL containers are homogeneous, so you are correct--you must store pointers to a common base class in order to collect objects of different (but related) types.
Also, you have mentioned that the user will input different information for each of the derived types. Run-time polymorphism allows you to treat base objects uniformly and still get the appropriate derived behavior.
class Item {
protected:
float price_;
//...
public:
virtualvoid ask_user() = 0;
};
class Meat : public Item {
float ounces_;
//...
public:
virtualvoid ask_user() {
// ask user for ounces, etc.
}
};
//...
// populate a cart of items
vector< Item * > cart;
cart.push_back( new Meat() );
cart.push_back( new Grain() );
cart.push_back( new Veg() );
// for each item, get information from the user
for( vector< Item * >::iterator i = cart.begin(); i != cart.end(); ++i )
{
(*i)->ask_user();
}
// clean up
for( vector< Item * >::iterator i = cart.begin(); i != cart.end(); ++i )
{
delete *i;
}
i have to use a virtual to print but not to populate. i understand the pointer part of it. but its the basics of making the code to populate where im stumped. using your base code the user would be asked... would u like to add meat...grain or veg to the inventory. they will select one and then the function has to ask them for a name, price... which are base class attributes. Plus one attribute from a specified class.