I am trying to create a program that takes food order and prints it out. I have my base class Food
which has a pure virtual function in it. Class Food has 2 sub
Starting with C++11, you can use std::reference_wrapper
too. It's very similar to @Mykola's answer, but uses references:
#include <functional> // for std::reference_wrapper
int main()
{
Dessert d("brownie");
Pizza p("BBQ delux");
std::reference_wrapper<Food> array = {d, p};
// just to see they're references, they have same memory addresses as
// the initial variables.
for (const Food &f : array) {
std::cout << &f << " ";
}
std::cout << "\n" << &d << " " << &p << "\n";
}
Unfortunately the same restriction applies to this and to the version with pointers. You need to have local variables defined, you can't just use anonymous objects here.
This won't work:
std::reference_wrapper<Food> array = {Dessert("brownie"), Pizza("BBQ delux")};
I like the simplicity of the answer from @Mykola. However, I prefer the look of the following:
int main()
{
Food* array[] = {
new Dessert("brownie"),
new Pizza("BBQ delux")
};
}
You cannot create instances of abstract classes, but you can assign concrete derived instances to pointers or references of the base class.
int main()
{
Dessert d("brownie");
Pizza p("BBQ delux");
Food* array[2] = {&d,&p};
}
then work with array
array[0]->print_food();
You need reference semantics for that, because Food arr[2];
tries to initialize the array with default values (which are abstract, thus not constructible).
I think std::array<std::unique_ptr<Food>, 2> arr;
should be the most natural to use in this case.
std::array<std::unique_ptr<Food>> arr = {
std::make_unique<Dessert>("brownie"),
std::make_unique<Pizza>("BBQ delux")
};
If you just want to loop over those two values, though, using initializer_list
would be easiest, I suppose.
for (auto f : std::initializer_list<Food*>{&d,&p})
f->commonMemberFunction();
Unfortunately it won't deduce the correct type from just {}
, but a helper could be created, I suppose,