I have this class named Enemy from which Ninja inherits its properties. In Ninja‘s attack function, I’m trying to call Ninja‘s getAttackPower function, but how do I get it. I tried calling this.getAttackPower but it didn’t work.
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
class Enemy {
int attackPower;
public:
virtual void attack() { cout << "I am attacking you!"; }
protected:
int getAttackPower() {
return attackPower;
}
void setAttackPower( int a ) {
attackPower = a;
}
};
class Ninja : public Enemy {
void attack() {
cout << "(minus " << getAttackPower() << " points).";
// .................. right here ......
}
};
int main() {
Ninja ninjaObj;
ninjaObj.setAttackPower(23);
ninjaObj.getAttackPower();
}
Here are the errors I’m getting:
void Enemy::setAttackPower(int) is protected
error: within this context
error: 'int Enemy::getAttackPower()' is protected
error: within this context
Your problem is in
mainnotattack. You set your access modifier forEnemy::setAttackPower(int)andEnemy::getAttackPower()toprotected. That means these methods are treated asprivateunless if you’re inside a class that extends Enemy.That means when you are in
mainit can’t accessninjaObj.setAttackPower(23)becausemainis outside the scope of any object.If you call
ninjaObj.attack(), however, it will also fail because you did not set an access modifier forNinja::attack(), so it defaults to private.To fix: add
public:in front ofNinja::attack(), and do not callEnemy::setAttackPower(int)orEnemy::getAttackPower()inmain.