As said try to avoid "new" in C++, I also tend to avoid 'C' style arrays (unless there is a clear benefit). 'C' style arrays don't have length checks and you can easily run into problems with writing out of bounds of the array and you will have to do some extra checking yourself.
#include <string>
#include <vector>
// not really sure what NEAT is
// but at least it can be made typesafe like this
enum class DrinkAttribute
{
UNKNWON,
NEAT,
};
struct Drink
{
std::string name = "no drink";
double price = 0.0;
DrinkAttribute attribute = DrinkAttribute::UNKNWON;
};
// put array and size information together including checks
struct Drinks
{
void add(const Drink& drink)
{
if (number_of_drinks < max_number_of_drinks)
{
drinks[number_of_drinks] = drink;
number_of_drinks++;
}
else
{
// some error handling here
}
}
Drink& get(std::size_t n)
{
if (n < number_of_drinks)
{
return drinks[n];
}
else
{
// some error handling here
// and return a drink representing no drink
// so all control paths return a value
// note I would probably just throw a std::invalid_argument exception here
// but I consider exception handling to be out of the scope of the question.
return no_drink;
}
}
static const std::size_t max_number_of_drinks = 10;
Drink drinks[max_number_of_drinks];
Drink no_drink;
std::size_t number_of_drinks = 0;
};
void ShowDrinksWithVector()
{
// to make dynamic collections of something you're bettor of using std::vector
// instead of arrays. This way you reuse tested code!
std::vector<Drink> drinks;
// at a drink to the collection of drinks
// the 3 arguments passed to emplace_back are used
// to construct an object of type Drink
drinks.emplace_back("Whole Milk", 2.50, DrinkAttribute::NEAT);
}
void ShowDrinksWithArray()
{
// this way you will have to write memory access checking code yourself
// that's why you will end up with an extra class (or you have to resort
// to using global variables)
Drinks drinks;
drinks.add(Drink{ "Whole Milk", 2.50, DrinkAttribute::NEAT });
auto drink = drinks.get(0);
}
int main()
{
ShowDrinksWithVector();
ShowDrinksWithArray();
}