I'm making a framework for what will eventually be a game. All objects in game are derived from game_object. I store everything in vectors; The _objects_ vector contains pointers to objects. The problem is when I call update the default update() function from game object is ran instead of the derived classes update() function. Is there anyway to fix this ?

/* _objects_ vector */
vector<game_object*> _objects_;

/* game_object class code */

class game_object
{
    public:

   /* ... */

    void update()
    {
        printf("Updating Base Class\n");
    }

};

/* cpong1 derived */

class cpong1 : public game_object
{
    public:

        /* ... */

        void update()
        {

        /* ... */

        printf("Updating cpong1 ...");

        }

        /* ... */
};



/* snippet of code that updates and draws all game objects */
unsigned int len=var::_objects_.size();
for (unsigned int i=0; i < len;i+=1)
{
        game_object * obj=var::_objects_.at(i);
        obj -> update();
        drip_blit( obj -> x , obj -> y, obj -> sprite ,::screen);
}

You need to use virtual functions:

Class Base{
     int val;
    ....
     virtual int doIt(){
          return val;
    }
};

Class Derived: public Base{
    ....
    virtual int doIt(){
        return val + val;
    }
}

Look up virtual functions and do some reading. Virtual functions are important and a powerful part of c++

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.