Thread: storing derived classes in a stl container

  1. #1
    Registered User
    Join Date
    Jul 2006

    storing derived classes in a stl container

    hi, im trying to write a program that parses messages using classes derived from a stub hook class.

    uint32_t HookManager::addReadHook (uint8_t id, ReadHook* hook) {
            if (!hook) {
                    printf ("warning: attempt to assign NULL read hook\n");
                    return -1;
            uint32_t hid = ids->newId ();
            rLookup.insert (std::pair<uint32_t, uint32_t> (hid, id));
            rHooks[id].insert (std::pair<uint32_t, ReadHook> (hid, *hook));
            printf ("insert: %p\n", hook);
            return hid;
    void HookManager::hookReadMessage (Message* m, Client* client)
            uint8_t id = m->getId ();
            for (RHookList::iterator it = rHooks[id].begin ();
                    it != rHooks[id].end (); ++ it)
                    (*it).second.func (m, client);
    class ReadHook
                    virtual ~ReadHook () {};
                    virtual void func (Message* m, Client* client) {}
    rHooks[i] is a map of hooks, and i want to iterate through the map calling each derived classes func. I used to store the derived hooks in a list<ReadHook*> and called the func using (*it)->func () and this worked. Whilst cleaning up the code i thought it would be nicer to store them as ReadHook, but now instead of the derived classes func being called the base classes func gets called. Ive tested this by defining the base func as {printf ("blah\n");}. Is there a way to do what i want do to, or is this a limitation of c++. thanks.

  2. #2
    and the Hat of Guessing tabstop's Avatar
    Join Date
    Nov 2007
    Once you store something as a ReadHook, then it IS a ReadHook and not a derived type -- the extra data/functions/et cetera are simply sliced away and discarded. In other words, once you hammer the square peg through the round hole, don't expect it to still be square on the other side.

  3. #3
    Registered User
    Join Date
    Jul 2006
    ok then, storing the pointers works so ill keep that.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. storing handler in container
    By l2u in forum C++ Programming
    Replies: 0
    Last Post: 08-12-2007, 04:03 PM
  2. List of derived classes
    By Asmodan in forum C++ Programming
    Replies: 1
    Last Post: 05-28-2002, 08:46 PM
  3. Replies: 2
    Last Post: 01-15-2002, 06:00 PM
  4. Inheiritance and derived classes
    By pecymanski in forum C++ Programming
    Replies: 2
    Last Post: 12-09-2001, 03:50 PM
  5. Pointers to derived classes.
    By sean in forum C++ Programming
    Replies: 3
    Last Post: 11-13-2001, 08:19 PM