0

I have a parent class called Resources and a child class called Food. I am storing different kinds of resources in an array that acts like my inventory. What I want to do is that when I traverse the inventory array if it finds a Food, I want to get the energyBoost value of the Food doing something like this: inventory[i].getEnergyBoost(); but It does not work because I cannot access the member variables of the child class from the parent object.

How can I solve this issue, Is it because I am doing something wrong about inheritance or is there a way to define a Parent object as a spesific subclass object while storing it as a Parent object.

Child Class Header:

 #include "resources.h"
    class Food:public Resources {
    protected:
        float energyBoost;

    public:
        Food();
        float getEnergyBoost();
    };

Parent Class Header:

enum type { none, Bones, Foods, tWater, Meds, Traps  };
class Resources {
protected:
    int size;
    char character;
    type t;
    int posX, posY;

public:
    Resources();
    Resources(Resources&);
    type getType(void);
    void setType(type);
    int getSize(void);
    void setSize(int);
    char getCharacter(void);
    void setCharacter(char);
    int getPosX(void);
    void setPosX(int);
    int getPosY(void);
    void setPosY(int);

};

Another Class:

float Archeologist::changeEnergy(void) {
    float energyBoost=0;
    for (int i = 0; i < inventorySize; i++) {
        if (inventory[i].getType() == Foods) {
            energyBoost += inventory[i].getEnergyBoost();   //Problem Here
        }
    }
    return energyBoost;
}
  • 3
    A base class cannot access the members of a derived class because the base class cannot know what has been added to a derived class. Look into `virtual` methods and makes sure you are not violating the [Liskov Substitution Principle](https://stackoverflow.com/questions/56860/what-is-an-example-of-the-liskov-substitution-principle) – user4581301 Jun 08 '20 at 20:48
  • 1
    Maybe [the CRTP pattern](https://stackoverflow.com/q/4173254/5987) could help in this case. – Mark Ransom Jun 08 '20 at 20:51
  • Add a `virtual float getEnergyBoost()` to the base class, returning 0. Then override it in `Food`. Then you can remove the check `if (inventory[i].getType() == Foods)` and simply always do `energyBoost += inventory[i].getEnergyBoost();` – rustyx Jun 08 '20 at 21:04

0 Answers0