a simplified example. I made the variables protected so derived classes can access their own variables. I can't access a referenced object in the derived class method SecAttack. Do I have to make Enemy a friend to the base class Player? But then shouldn't I make the variables private?
class Player
{
private:
char *name;
protected:
int health;
int damage;
public:
void attack(Player *prey)
{
prey->health-= damage;
}
//friend class Enemy;
};
class Enemy: public Player
{
public:
void heal() //self access test, ok
{
health+= 10;
}
void SecAttack(Player *Prey) // cant access a Player object
{
Prey->health -= (damage+5);
}
};
@IceThatJaw
im confused, the compiled one you gave me will attack itself?
ive read to use protected on variables for derived classes.
I want to access a object through the function SecAttack()
I answered your post too quickly.
You are trying to access a Player object when you should be accessing an Enemy object.
You can only access protected data within the structure or from a structure that is derived from it.
Just change void SecAttack(Player *Prey)
to void SecAttack(Enemy *Prey)
class Player
{
private:
char *name;
protected:
int health;
int damage;
public:
Player(char *n = "Player", int hp = 100, int dmg = 20)
:name(n), health(hp), damage(dmg){}
void attack(Player *prey)
{
prey->health-=damage;
}
friendint main(); //just to test
};
class Enemy: public Player
{
public:
Enemy()
:Player("Enemy",90,15){}
void attack(Enemy *prey)
{
prey->health -= damage;
}
friendint main(); // just to test
};
void main()
{
Player User("User",100,20);
Enemy Troll;
cout << User.health << endl;
cout << Troll.health << endl;
Troll.attack(&User); // Error: player is incompatible
}
1 2 3 4 5 6 7 8 9 10 11 12
class Player ...
void takedmg(int dmg)
{
health-= dmg;
}
class Enemy ...
void attack(Enemy *prey)
{
prey->takedmg(damage+5);
}
this works, doesn't seem efficient though. the other alternative is to friend the derived class. whats the best alternative? is using friend allot bad?
You are duplicating the method Attack when you don't have to. It would make sense if an Enemy's attack had different code because you could use polymorphism but in your case it is just redundant code.
If you want to get at things like health in your main function then you need to provide public getter methods that will return copies of them or just make make your class public or use a struct.