Reputation: 1480
I haven't done much polymorphism in c++, and it's been a long time since I done it in other languages, so I'd like some input as to if what I'm trying to achieve is even possible.
I have a class "Entity", and several other 'specialized' sub-classes which inherit Entity. These sub-classes all have completely different methods (not overriding/reimplementing the same one), as they need to perform different functions.
I'm looking for a way to organize all of these "Entities" into a single list. If I were to create a single array of type "Entity" and assign the sub classes to the array, I would no longer be able to call any of the sub-class functions, only the parent "Entity" functions.
The only messy way I can immediately think of is to create an array for each sub-class, which doesn't seem that neat at all when I think of the amount of sub-classes I intend to make, not to mention the amount of memory the application would need to allocate.
Is there any way to cleanly achieve something similar to what I'm trying to do?
Upvotes: 1
Views: 329
Reputation: 16824
If your Entity
subclasses really do completely different things, then it may be worth looking again at your design.
The best way to solve this problem would be to add a (perhaps pure) virtual method on the Entity
base class, something like
struct Entity
{
virtual void do_stuff() = 0;
virtual ~Entity() {}
};
struct En1 : public Entity
{
// En1-specific methods
void method1();
void method2();
// Override
void do_stuff() override {
method1();
method2();
}
};
You can then create an array holding pointers to Entity
s, i.e.
std::vector<std::unique_ptr<Entity>> vec;
vec.emplace_back(new En1);
vec.emplace_back(new En2);
for (auto&& e : vec) {
e->do_stuff();
}
The alternative would be to try to use dynamic_cast
or typeid
to work out which subclass you're dealing with at runtime, but this is fragile and hard to expand in future and certainly not recommended.
Upvotes: 2
Reputation: 7769
Create your object of any derived classes that you wish, and then store there addresses in an array of Entity pointers.
Use the dynamic_cast
or static_cast
operator to downcast the pointers in the array to the appropriate derived class and use this casted pointer to call your derived class methods.
Upvotes: 1