I'm watching tutorials from thenewboston on youtube ,and I have few questions about Polymorphism. Here is his code:
#include <iostream>
using namespace std;
class Enemy{
protected:
int attackPower;
public:
void setAttackPower(int a){
attackPower=a;
}
};
class Ninja:public Enemy{
public:
void attack(){
cout<<"I am a ninja,ninja chop! -"<<attackPower<<endl;}
};
class Monster:public Enemy{
public:
void attack() {
cout<<"monnster must eat you!!! -"<<attackPower<<endl;
}
};
int main()
{
Ninja n;
Monster m;
Enemy *enemy1=&n;
Enemy *enemy2=&m;
enemy1->setAttackPower(29);
enemy2->setAttackPower(99);
n.attack();
m.attack();
}
My question is : Can I write the code in main() like this(or shouldn't I and WHY??):
Ninja n;
Monster m;
//Enemy *enemy1=&n;
//Enemy *enemy2=&m;
//enemy1->setAttackPower(29);
//enemy2->setAttackPower(99);
n.setAttackPower(99);
m.setAttackPower(29);
n.attack();
m.attack();
Can I write the code in
main()like this [...]
Absolutely, you can! The reason for this is that your new example does not use polymorphic behavior. Unlike the original example, which hid the knowledge of run-time type of Enemy objects from compile-time code, your rewritten code keeps types available.
Here is what's not going to work without a pointer or a reference:
void setPowerAndAttack(Enemy enemy, int power) {
// ^^^^^^^^^^^
// This is not going to work without pointer/reference
enemy.setAttackPower(power);
attack();
}
...
Ninja n;
Monster m;
setPowerAndAttack(n, 99);
setPowerAndAttack(m, 29);
Even though the code would compile, Enemy in setPowerAndAttack is not going to exhibit polymorphic behavior due to object slicing.
You need to make enemy a pointer or a reference to keep polymorphic behavior:
void setPowerAndAttack(Enemy& enemy, int power)
// ^
Very Important: You need to make attack function virtual in the Enemy class in order to have any polymorphic behavior at all. This is not clear from watching the video:
class Enemy {
protected:
int attackPower;
public:
void setAttackPower(int a) {
attackPower=a;
}
virtual void attack(); // <<== Add this line
virtual ~Enemy() = default; // <<== Add a virtual destructor
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With