Confused about Polymorphism

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
    #include <iostream>
    #include "Mother.h"
    #include "Daughter.h"
    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;
    }
    };

    class Monster:public Enemy{
    public:
    void Attack()
    {
    cout << "I am a monster and im going to eat you!!!, NAWM NAWM MUNCH MUNCH  -" << AttackPower;
    }
    };
    int main(){
    Ninja n;
    Monster m;
    Enemy *enemy1 = &n;
    Enemy *enemy2 = &m;
    enemy1->SetAttackPower(29);
    enemy2->SetAttackPower(300);
    n.Attack();
    m.Attack();

}


`
Heres my question. Why cant this:

1
2
3
4
5
6
7
8
9
 int main(){
    Ninja n;
    Monster m;
    Enemy *enemy1 = &n;
    Enemy *enemy2 = &m;
    enemy1->SetAttackPower(29);
    enemy2->SetAttackPower(300);
    n.Attack();
    m.Attack();



be this instead of using pointers???

1
2
3
4
5
6
7
8
9
    int main(){
    Ninja n;
    Monster m;
    Enemy enemy1 = n;
    Enemy enemy2 = m;
    enemy1.SetAttackPower(29);
    enemy2.SetAttackPower(300);
    n.Attack();
    m.Attack();


Maybe its because i'm still slightly confused about pointers....Could someone please explain this for me?
In your second snippet on line 4 and 5, you declare Enemy instances, which only have the data for an Enemy; this means they have no space to store anything additional that a Ninja or Monster has. Thus, that assignment is no good.

The first snippet works because when you declare a pointer, you say the pointer simply will refer to something of the Enemy type; i.e., something that can do everything that an Enemy can do. Since Ninja and Monster inherit from Enemy, they fulfill this requirement and the assignment is good.

Also, to see the polymorphism in action, use the enemy1/2 pointers on line 8 and 9 of your first snippet; notice that the Ninja/Monster versions of Attack() are called even though you are calling them via an Enemy pointer.
So are you saying any time i create an object, and set it equal to an object from another class, I have to pass a pointer by reference because without the pointer. The second object cant access the first object?
> notice that the Ninja/Monster versions of Attack() are called even though you are calling them via an Enemy pointer.
That wouldn't compile.

@OP: learn to indent.
In the last snip, `enemy1' and `n' are two different objects, with no relationship
Topic archived. No new replies allowed.