vectors and inherited classes

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • DevInCode
    New Member
    • Apr 2008
    • 55

    vectors and inherited classes

    My class is Creature which has subclass called Human

    I have a vector of * creatures
    vector<Creature > * creatures .....

    It is filled with dozens of creature objects. However I want to make one of those creatures into a Human, how can I do this as the vector isn't of that type.

    This doesn't work
    vector->at(10) = new Human();
  • newb16
    Contributor
    • Jul 2008
    • 687

    #2
    Use vector<shared_p tr<baseClass> > where creature and human inherit baseClass.

    Comment

    • weaknessforcats
      Recognized Expert Expert
      • Mar 2007
      • 9214

      #3
      Originally posted by DevInCode
      vector<Creature > * creatures .....

      You need to derive Humans from Creature.

      Then you need a vector of Creature* and not a pointer to a vector<Creature >.

      Like this:

      Code:
      vector<Creature*> creatures.
      Then your code should work.

      Using shared_ptr is not standard C++ yet. But it is a good idea.

      Comment

      Working...