So the problem here is that a Player requires a Card, therefore, the Card needs to be declared on top of the Player class. Further on my Card class uses a function that needs a Player pointer parameter. To remove other errors I used a forward declaration above the Card class to make the Player class visible. I'm also using a pointer to a Player in the attackEnemy function parameters as the size of the object cannot be known at that point with only a forward declaration. When i try to invoke a function from the passed Player pointer in the attackEnemy function inside the Card I get a compile error. The error is error C2227: left of '->looseHealth' must point to class/struct/union/generic type.
This is the program:
#include "stdafx.h"
#include <iostream>
using namespace std;
class Player;
class Card {
private:
int attack;
public:
Card() {
this->attack = 2;
}
void attackEnemy(Player* i) {
i->looseHealth(this->attack); //error is here
}
};
class Player {
private:
string name;
int health;
Card* playersCard;
public:
Player(string name) {
playersCard = new Card();
this->name = name;
}
void looseHealth(int x) {
cout << "lost health -" << x << " points" << endl;
health -= x;
}
};
int main()
{
Card* opponedsCard = new Card();
Player* player1 = new Player("player 1");
opponedsCard->attackEnemy(player1);
return 0;
}
The attackEnemy
uses a incomplete type Player
, which is forward declared.
Just declare void attackEnemy(Player* i);
in Card
class and
move
void attackEnemy(Player* i) {
i->looseHealth(this->attack); //error is here
}
After definition of Player
class
void Card::attackEnemy(Player* i) {
i->looseHealth(this->attack); //error is here
}