//Enemy.h
//Enemy SuperClass
class Enemy
{
public:
Enemy();
~Enemy();
void setEnemyHealth(int nEHealth){
nHealth = nEHealth;
}
void setEnemyAttack(int nEAttack){
nAttackPower = nEAttack;
}
void setMoveSpeed(int nEMoveSpeed){
nMoveSpeed = nEMoveSpeed;
}
void CyborgEnemy();
void NinjaEnemy();
protected:
int nHealth;
int nAttackPower;
int nMoveSpeed;
};
class Cyborg : public Enemy
{
public:
void getCyborg(){
cout << "I am a Cyborg...\n";
cout << "My health is: " << nHealth << endl;
cout << "My attack power is: " << nAttackPower << endl;
cout << "My move speed is: " << nMoveSpeed << endl;
}
};
class Ninja : public Enemy
{
public:
void getNinja(){
cout << "I am a ninja...\n";
cout << "My health is: " << nHealth << endl;
cout << "My attack power is: " << nAttackPower << endl;
cout << "My move speed is: " << nMoveSpeed << endl;
}
};
There are some other problems with your code. Enemy::CyborgEnemy() creates a local variable called newCyborg and sets it up, but that variable gets destroyed when the method exits. Enemy::NinjaEnemy() is similar. iF you want to create a Cyborg or a Ninja, then just do it:
That is not quite how polymorphism is done. The base class should not know anything about the derived classes.
You could write tomorrow ten new enemy classes. Why should you have to change the class Enemy then?
Perhaps you derive a WhiteNinja from Ninja. Would you change Ninja and Enemy because of that?
The CyborgEnemy() is a member of class Enemy. You do need to have an Enemy object, whose member to call.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
#include <vector>
#include <list>
#include <string>
#include "Enemy.h"
usingnamespace std;
int main() {
size(); // error; while vector, list, and string all have member size(), this call lacks object
CyborgEnemy(); // error; while Enemy has a member, this call lacks object
std::string foo;
Enemy bar;
foo.size(); // ok
bar.CyborgEnemy(); // ok, but ...
return 0;
}
... but that bar does nothing and it makes no sense to have one there. Classes can have static members. In polymorphism the virtual members are important. Study both.
You do repeat a lot of code unnecessarily. If the classes would have constructor that takes the three ints, you would not need to call all those set* on creation.
The Enemy should have a method to show the three attributes. Then they could be private rather than public.
It seems I have a lot more to learn when it comes to Polymorphism... But I will get there in the end.
To dhayden: Thank you for the feedback. I implemented the change to the main instead of creating an entire new function for it. It works well, but it still got me a bit more confused, so I guess i gotta do more studying on it :).
To keskiverto: I didn't fully understand what you mentioned and it's probably cause I don't actually know polymorphism yet. I will get back to learning and re-read your question. I did not know about Static or Virtual members, so guess I have a lot of studying to do...