So I have the main parent class called item
and that class has 2 child classes called book
and periodical
. The ideas behind what I am trying to do is have a polymorphic array or a polymorphic vector that would be able to do something like this:
Now the example is in C# (but I want to do it in C )
item [ ] items = new items [100];
items[0] = new book();
items[1] = new periodical();
for (int i = 0; i < items.size; i ) {
items[i].read();
}
Like I said, the small example code is in C# but I want to do this in C but I am not sure how to go about going it. I wanted to use arrays but I'm my research, I haven't found a clear way of how to accomplish this. I also thought if vectors were possible to use or this but I was not sure about that either.
CodePudding user response:
Here is an example (if you have questions let me know):
#include <iostream>
#include <memory>
#include <vector>
class Item
{
public:
virtual ~Item() = default; // base classes with virtual methods must have a virtual destructor
virtual void read() = 0;
};
class Book final :
public Item
{
public:
void read() override
{
std::cout << "book read\n";
}
};
class Periodical final :
public Item
{
public:
void read() override
{
std::cout << "periodical read\n";
}
};
int main()
{
std::vector<std::unique_ptr<Item>> items;
// use emplace_back for temporaries
items.emplace_back(std::make_unique<Book>());
items.emplace_back(std::make_unique<Periodical>());
// range based for loop over unique_pointers in items
// use const& so item cannot be modified and & to avoid copy of unique_ptr (unique_ptr doesn't have a copy constructor)
for (const auto& item : items)
{
item->read();
}
return 0;
}