mercredi 19 avril 2017

Call polymorphic function from vector of pointer to base class

I have a structure of classes that looks like:

      1
     / \
    2   3
   |||  ||
  4 5 6 7 8

and a vector that holds pointers to 1. 1 has three pure virtual functions, all of which are overridden to return default values in 2 and 3 then specific ones in 4 through 8.

The vector is controlled through a class and the two offending functions:

class Vector
{

public:
    Vector();

    void vectorAdd(*Food food)
    {
        mList.push_back(food);
    }


    //The two offending functions. The functions they point to are pure
    //virtual in the Food class and overridden in the derived classes.

    string getDescription(size_t index)
    {
        return mList[index]->getDescription;
    }


    double getPrice(size_t index)
    {
        return mList[index]->getPrice;
    }
private:
    vector<Food*> mList;
};

I'm adding to the vector from int main by:

list.vectorAdd(&Spaghetti);

The code all compiles, but whenever I call Vector::getDescription(index) or Vector::getPrice(index) I get a Debug Error with no information as to what went wrong.






Comments
0 Comments

0 commentaires:

Enregistrer un commentaire