what am I doing wrong

Hi guys I have a small program here that sets a power of an attack,now this question is mainly about pointers so I made an enemy object and set it to the address of a ninja object,now it does allow me to set the power with the enemy object but when I try this " n.attack() " it does not work,I thought by setting the pointer to the n object that it would/could set the properties of the ninja object n because I thought I was directly accessing the object,how come this won't work,am I thinking wrong here?

Thanks

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

  #include <iostream>

using namespace std;

class enemy{

   public:
       void setAttackPower(int a){

           attackPower = a;
       }
   protected:
    int attackPower;

};


class ninja : public enemy{

  public:

    void attack(){

        cout << "ninja attack" << attackPower;
    }

};

class monster: public enemy{

 public:
    void attack(){

        cout << "I am a monster" << attackPower;

    }
};

int main()
{
   ninja n;
   enemy *enemy1 = &n;
   enemy1->setAttackPower(20); // working fine up to here,this is where I 
  //  thought it would set the n objects attackPower to 20 but does not
   n.attack(); 

}


Last edited on
http://ideone.com/uagjnH

Hey look. n's attack power is 20.

Of course, it might've been 20 before the call to setAttackPower.
but when I try to call n->attack; it does not work I'm guessing this is because the attackPower for n has not been set?
it does not work


From cire's demonstration, sure looks like it works. In what way does it "not work"?

Also, why is line 44 not n.setAttackPower(20); ?
Last edited on
but when I try to call n->attack;


Well, n isn't a pointer, so of course you can't dereference it with ->. If you could dereference it with -> that wouldn't be a function call as it's missing the required parentheses. n.attack() works, though, as demonstrated.
thanks cire and Moschops,it does actually work I'm not sure what was going wrong for me earlier haha thanks =)
Topic archived. No new replies allowed.