Hi Y'all.
Another beginner question, although I'm getting into the esoterics here. As I mentioned in my post last week, I am going through Bucky Roberts's 9+ hour video and have gotten up to the section on polymorphism. (Yes, I will look into learnc.com later.) Not yet done with the lesson (so I haven't gotten up to the real meat) but I'm having trouble with the intermediate setup.
Following Bucky's example closely (but not aping everything) I created a base class named
Enemy with a protected variable
attackPower and public method
setAttackPower(). I then created two derived classes named Nonja and Monster. Each has a method called attack().
I created a variable each derived class and called setAttackPower for each of these variables, with a different value to set for its instance of variable attackPower. Here's the code; results after the code section.
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
|
#include <iostream>
using namespace std;
class Enemy
{
protected:
int attackPower;
public:
void setAttackPower(int a)
{
int attackPower = a;
cout << "Enemy::attackPower has been set to " << attackPower << endl;
}
void showAttackPower()
{
cout << "Current value of attackPower = " << attackPower << endl;
}
};
class Ninja: public Enemy
{
public:
void attack()
{
cout << "I am Ninja. Must attack you at level: " << attackPower << endl;
};
};
class Monster: public Enemy
{
public:
void attack()
{
cout << "I am Monster. Must eat you at level: " << attackPower << endl;
};
};
int main()
{
Ninja nin;
Monster mon;
nin.setAttackPower(29);
mon.setAttackPower(99);
nin.attack();
mon.attack();
return 0;
}
|
When I run in codeblocks I get this output:
Enemy::attackPower has been set to 29
Enemy::attackPower has been set to 99
I am Ninja. Must attack you at level: 4354206
I am Monster. Must eat you at level: 2686868 |
YIKES! What happened? Where did those crazy values come from?
On the other hand, when I run the same code under the C++ compiler in my CygWin64 environment, I get this:
Enemy::attackPower has been set to 29
Enemy::attackPower has been set to 99
I am Ninja. Must attack you at level: 0
I am Monster. Must eat you at level: 0 |
Funny, I did the same thing again and got a
different result. Time for sanity self-check? ;-)
Either way, it ain't what I set it to. What am I doing wrong?
(BTW, I'm not getting the preview or tags by clicking the icons. My apologies for any bad formatting.)
Thanks for help here.
-- Jake S. (Pronounce that out loud and you'll know how I'm feeling. :-)