David G
David G

Reputation: 96835

How to access object properties from within object method?

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

Upvotes: 0

Views: 8336

Answers (1)

Hans Z
Hans Z

Reputation: 4744

Your problem is in main not attack. You set your access modifier for Enemy::setAttackPower(int) and Enemy::getAttackPower() to protected. That means these methods are treated as private unless if you're inside a class that extends Enemy.

That means when you are in main it can't access ninjaObj.setAttackPower(23) because main is outside the scope of any object.

If you call ninjaObj.attack(), however, it will also fail because you did not set an access modifier for Ninja::attack(), so it defaults to private.

To fix: add public: in front of Ninja::attack(), and do not call Enemy::setAttackPower(int) or Enemy::getAttackPower() in main.

Upvotes: 3

Related Questions