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?
#include <iostream>
usingnamespace 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();
}
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.