Unsure about calling a method in a derived class

Started by
5 comments, last by Rattrap 16 years, 10 months ago
I have a class called Component that will act as the base class for the objects in my game. I have a Component Manager that stores all the Components in a list and calls the update() method for them. My question is, when I make a class that derives the Component class, how do I call the update method for it from the manager? If I try to call update() in the manager, it looks to Component for an update method. I've been trying to think out this design and considered maybe using a template class for the Component. But I don't know if this is a good method or not and I wouldn't know how to store a list of template class objects of an unknown type. Here is a watered down version of what I have so far
class Component {
public:
  Component(string id) : ID(id) {}
  string getID() { return ID; }
  void update() {} // only here because I get a compile error without it
private:
  string ID;
};

class Manager {
public:
  list<Component> objects;
  // methods for adding, removing components
  void update() { 
    // iterate through the list...
    iterator->update(); // calls the update method in the component class, but I need it to run the code in the derived objects update method
    // go to next element
  }
};

class Dog : public Component {
public:
  Dog(string s) : Component(s) {}
  void update() { cout << "Updating dog"; }
};


int main() {
  Dog noodles("dog1");
  manager.add(noodles);
  manager.update(); // won't run the update code for noodles
}

Any help would be great.
Advertisement
Dynamic dispatch only works via pointers or references, and since you can't store references in SC++L containers, you'll have to store pointers.

Also note that this kind of overly-homogenized system of treating every single game object exactly the same is usually not ideal.
Hmm, well, I'm just looking for a way to update and draw all the game objects on each frame. Is there a better method for doing this?
Storing pointers is the first step, but you also need to make the update() function virtual in the base class (and also add a virtual destructor). If you don't know what this means, look for information about polymorphism and virtual functions.
Ok thanks Gage64, I'll change that.

Is it better to use pointers or references...like in general? Or does it depend on the situation?
it depends on the situation. For example, like jpetrie said, you can't store references in containers so in this case pointers are the only choice.
And probalby want to make those pointers smart pointers, to be sure they get deleted propertly from the container.

"I can't believe I'm defending logic to a turing machine." - Kent Woolworth [Other Space]

This topic is closed to new replies.

Advertisement