1

I'm working on a game / simulation, and dealing with managing all the creatures in the game. There is one base class Creature from which different kinds of creatures take inheritance from.

In early versions of this code, where I just used the base class on its own as a generic for any given creature, I had a private static vector that kept a phonebook if you will of all the creatures that exist in the game. This was handled by the Creature's constructor, adding the new creature's address onto the stack. Simple enough.

Where I'm getting a mental block is when I introduce inheritance. If I proceed to adapt the Creature class to be a base class (move the vector to protected status I would imagine?), and from there define some arbitrary child classes of Monkey, Bear, and Tiger... When I create an instance of a class that inherits from Creature, will it -also- be added to the pointer vector in the Creature parent class? Perhaps more directly, does creating an instance of one of these child classes also call the constructor of the parent class?

Am I on the right train of thought, or what would I have to do to achieve this behavior? I can provide more specific details if needed.

Thanks.

--

My idea behind doing things this way, for one example is graphics. That way I can cycle through all the creatures that exist and via polymorphism call functions on each of the creatures that return their sprites, X Y location, etc.

user2717676
  • 79
  • 1
  • 3
  • In need of Factory Pattern ? http://sourcemaking.com/design_patterns/abstract_factory/cpp/1 – Arunmu Oct 15 '13 at 17:00

1 Answers1

1

This definitely works, as long as your vector store pointers Creature* and not Creature inside your std::vector. Otherwise object slicing would occur since the vector reserve the space for just Creature and every additional feature of subclasses is discarded

Regarding the constructor call stack it is fairly straightforward:

class A {
  private:
    int aField;
  public:
    A(int aField) : aField(aField) { }
};

class B : public A {
  private:
    int bField;
  public:
    B(int aField, int bField) : A(aField), bField(bField) { }
};
Community
  • 1
  • 1
Jack
  • 131,802
  • 30
  • 241
  • 343
  • Yeah! I'm calling it out in Creature as vector creatureStack;, an array of pointers to Creatures. Thanks a lot. I'll be sure to save a copy of that code for reference. :) – user2717676 Oct 15 '13 at 17:02
  • Mind that if you have to manage many allocations and deallocations of `Creature` instances then a custom memory pool could be handy to avoid heap fragmentation. You will have to solve the fact that subclasses have different sizes but there is much about it if you search over internet. – Jack Oct 15 '13 at 17:03