0

Below are the .cpp versions of my character class and its subclasses. I am trying to get the attack() function to work. I made some changes and the current error deals with "invalid use of ‘this’ in non-member function" in the adjustHP() function. In my main class, I am instantiating a Warrior object which the player plays as and the Goblin as an uncontrollable enemy.

character.cpp

character::character(double hp ,double atk, double defense, double speed){
    this->hp= hp;
    this->atk = atk;
    this->defense = defense;
    this->speed = speed;
}

double character::getHP() {
    return this->hp;
}

double character::getATK() {
    return this->atk;
}

double character::getDEFENSE() {
    return this->defense;
}

double character::getSPEED() {
    return this->speed;
}

warrior.cpp

Warrior::Warrior():character(hp,atk,defense,speed) { // Constructor
    this->hp= 50;
    this->atk = 50;
    this->defense = 50;
    this->speed = 50;
}

void Warrior::adjustHP(double adjustBy) {
    this->hp = this->hp - adjustBy;
}

void Warrior::attack(character* enemy) {
    enemy->adjustHP(10);
}

goblin.cpp

Goblin::Goblin() : character(hp,atk,defense,speed) { // Constructor
    this->hp= 60;
    this->atk = 40;
    this->defense = 40;
    this->speed = 40;
}

void adjustHP(double adjustBy) {
    this->hp = this->hp-adjustBy;
}

void Goblin::attack(character* playerChoice ) {
    playerChoice->adjustHP(10);
}
김선달
  • 931
  • 3
  • 18
  • 1
    Please provide a minimal reproducible example – Moia Jun 09 '20 at 07:06
  • The error message should point you to the exact line of code, and make it quite obvious. – dxiv Jun 09 '20 at 07:07
  • Aside: at the moment, there's no point to having 3 classes, you can just have `character Warrior()` and `character Goblin()` free functions that do the same thing – Caleth Jun 09 '20 at 08:15
  • @Caleth I am attempting to use a few design patterns for practice (Strategy here in particular) and will expand upon the program to differentiate Warrior and Goblin. – lucky_batra Jun 09 '20 at 08:37
  • I think strictly speaking your `Warrior::Warrior` and `Goblin::Goblin` have undefined behaviour, because you use data members before initialising them. `Warrior::Warrior() : character(50, 50, 50. 50) {}` and `Goblin::Goblin() : character(60, 40, 40, 40) {}` are correct – Caleth Jun 09 '20 at 08:41

2 Answers2

1

Compare your

void adjustHP(double adjustBy) {

with what you intended:

void Goblin::adjustHP(double adjustBy) {

C++ doesn't prevent you from defining an unrelated free adjustHP function in goblin.cpp and leave Goblin::adjustHP undefined in that file.

rubenvb
  • 69,525
  • 30
  • 173
  • 306
1

In goblin.cpp you defined adjustHP as a non-member function. It should have been:

void Goblin::adjustHP(double adjustBy) {
this->hp = this->hp-adjustBy;
}
RvdK
  • 18,577
  • 3
  • 56
  • 100