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;
}