For my Intro to CS class we're making a short game where the different characters have to fight each other (attack points and defense points are generated by rolling a certain number of dice). One of the characters is a Shadow which overrides the base class defense function in order to generate a 50% chance of not being hit. I tested the overridden function in isolation and it works but when I call it in my combat function it just used the base class version of defense, despite the fact that the character playing is a Shadow. Any ideas? I suspect it has something to do with pointers. And yes the base class defense function is declared as virtual.
Update: Here is the base class and shadow class -- I removed member data and functions that are not relevant to the question.
//The Character Class
class Character
{
protected:
Dice AttackDie;
Dice DefenseDie;
public:
//The Constructor
Character(string,int,int,int,int,int,int);
virtual int attack();
virtual int defend() const; //I've tested it with and without const, it still doesn't work
int getSP(); //StrengthPoints Accessor
string getName();
friend void combat(Character, Character);
};
//Shadow subclass
class Shadow: public Character
{
//Will override defense
public:
Shadow(string,int,int,int,int,int,int);
//Override the defense function
int defend() const;
};
void Combat(Character char1, Character char2)
{
//Set up the players so that they can alternate
Character* player1 = &char1;
Character* player2 = &char2;
//While loop for combat;
while (char1.getSP() > 1 || char2.getSP() > 1) //Play until a character dies
{
//Variables for combat
int attacksum = 0;
int defensesum = 0;
int result = 0;
int damage = 0;
int hurt = 0;
attacksum = player1->attack(); //Generate attack value
//Generate Attack Points
cout << player1->getName() << " attack points are " << attacksum << endl;
//Generate Defense Points --- This does not call the overriden function when player2 is a Shadow
defensesum = player2->defend(); //Generate defense value
//Display the defeense
cout << player2->getName() << " defense points are " << defensesum << endl;
}