I need to call the correct function from an object of a sub-class. Both the super-class and the sub-class have this function but the sub's is different. I am unable to make function virtual because I do need to be able to sometimes create an object of that type. The super-class also has inherits from its own super-class.
class Character
{
private:
//A bunch of private member variables
public:
//Some other functions + constructor
virtualvoid save() const = 0 {/*Definition of save()*/}
virtualvoid attack(weapon blade, bool advan = false, bool disadvan = true) const = 0 {/*Definition of attack*/}
};
class Fighter : public Character
{
private:
//A few added member variables
public:
//A few added functions
void save()
{
//Added save statements for a fighter
Character::save();
}
void attack(weapon blade, bool advan = false, bool disadvan = false) {/*A little added flair and then calls Character::attack() with certain paramters.*/)
};
class BattleMaster : public Fighter
{
private:
//A few more member variables
public:
void save() {A bit more added statements
Fighter::save();}
void attack(weapon blade, bool advan = false, bool disadvan = false)
{
//A few more added statements
Character::attack(); //With special parameters
}
};
int main()
{
Character* player = createCharacter(); //Creates a character based on user input.
return 0;
}
So I have no idea of knowing what class the object will be until runtime. Is there anyway I can have a type of BattleMaster call the correct function if I later call something like player.save();? Or am I just going at this completely incorrectly?
Right my bad. But even if I declare the function in Fighter as virtual it still is called when I have player = new BattleMaster(); instead of calling BattleMaster.save();
I disagree. It is not. Here is some code in which I use player = new BattleMaster();
and you can see that when I call save on it, the Battlemaster save is called.
Don't forget that when you override a virtual function, it has to be the same. Same name. Same const on the end.
That being said, you can add in the keyword override to clearly show that the child is overriding a virtual parent method. If the parent didn't have this method, then it would be a syntax error, which could be useful at compile time.
#include <iostream>
usingnamespace std;
class Character
{
public:
virtualvoid Save() = 0;
};
class Fighter : public Character
{
public:
void Save() override
{
cout << "Fighter save\n";
}
};
class BattleMaster : public Fighter
{
public:
void Save() override
{
cout << "Battlemaster save\n";
}
};
int main()
{
//Character c; // Not allowed since all its methods are pure
Fighter f;
BattleMaster b;
f.Save();
b.Save();
return 0;
}
That bit on the end, "= 0", specifies that the function is "pure virtual". It means that there will be NO IMPLEMENTATION provided, and that the class this belongs is abstract.