Hey guys, this is a bit of a strange question, but is it possible to access the variables within the cStats class through a pointer of type cCharacter? If so, how would I do this? I have tried searching around but not really sure how to structure a good question to find good results so hopefully someone here can help.
Reason I'd like to do this is because I'm doing an exercise and it says:
"Create a class "Character". Enemy and Player will inherit from it.
GetHit function will be virtual, so you can override them in the children.
Put all redundant code into the parent class (ie, they both have cStats and the same functions)."
In the previous exercise it says to make a class called cStats, and now it's saying make a class called cCharacter and make the monster and player both inherit from it, but also inherit all the cStats variables. So I think it's saying keep the cStats class and somehow access those variables through the cCharacter class. Hopefully that makes sense.
This is just a part of the full code but it's all that's required. Obviously the cout statements in main wouldn't work as it would say 'class cCharacter' has no member named 'iHP'.
So yes, I could just store all of cStats' variables inside cCharacter, but I'd ideally like to be able to access cStats' variables through a cCharacter pointer.
Thanks :)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
|
class cCharacter{
public:
virtual void fGetHit(){}
virtual int fDisplayHP(){ return 0; }
};
class cStats{
public:
int iHP;
int iATK;
int iDEF;
int iSKIL;
};
class cMonster: public cStats, public cCharacter{
public:
cMonster(int a){
iHP = a;
}
void fGetHit(int a, int b){
iHP = iHP - a;
if(b == 1)
cout << "\nYou hit the monster for " << a << " damage!\n";
else
cout << "\nYou threw a fireball at the monster for " << a << " damage!\n";
}
int fDisplayHP(){
return iHP;
}
};
class cPlayer: public cStats, public cCharacter{
public:
cPlayer(int a){
iHP = a;
}
void fGetHit(cMonster &monst){
iHP = iHP - monst.iATK;
cout << "\nThe monster hit you for " << monst.iATK << " damage!\n";
}
void fHealSelf();
int fDisplayHP(){
return iHP;
}
int fFireball(){
return iSKIL;
}
string sClass;
};
int main(){
cPlayer oPlayer(100);
cMonster oMonster(100);
cCharacter* pPlayer = &oPlayer;
cCharacter* pMonster = &oMonster;
cout << pPlayer->iHP << endl;
cout << pMonster->iHP << endl;
return 0;
}
|