Search code examples
c++classheader-files

Class does not name a type error in C++ Code


I'm trying to make a small game in C++ and I'm already running into problems adding adding my Player class into my Game class. I thought this was a circular dependency issue, but forward declaring the class didn't help the issue!! I've looked everywhere and just can't figure it out so hoping to get some understanding as to why this doesn't work. I'm only including the headers because all I have in the source code at the moment are my constructor definitions"

Game.h

#ifndef GAME_H_INCLUDED
#define GAME_H_INCLUDED

#include "Player.h"

//only one instance of a game should be running
//make singleton class
class Game {
private:
    bool playing;
    Player * Player = 0;
    static Game * inst;
    Game() {}
public:
    Player * GetPlayer() { return Player; } //Getting a "Player does not name a type" error here???
    void AddPlayer(int health, int mana, int strength) { Player = new Player(health, mana, strength)}
    bool StillPlaying() { return playing; }
    void EndGame() { playing = false; }
    static Game * GetInstance();
    void StartGame();
};

#endif // GAME_H_INCLUDED

Player.h

#ifndef PLAYER_H_INCLUDED
#define PLAYER_H_INCLUDED

#include "Subject.h"

class Player : public Subject {
protected:
    int health;
    int mana;
    int strength;
public:
    Player(int health, int mana, int strength);
    int GetHealth() { return health; };
    int GetMana() { return mana; }
    int GetStrength() { return strength; }
    void TakeDamage(int enemyStrength) { health -= enemyStrength; }
    void Attack();
    void Heal();
    void Event();
};

#endif // PLAYER_H_INCLUDED

The errors are showing up in the Game.h file, and specifically it says that " 'Player' does not name a type " on the GetPlayer() function. I'm really confused because it doesn't give me an error when I declare the Player member variable??


Solution

  • You have a class Player and a member of Game named Player. Once the member declaration is encountered, all references to Player within the Game class will be to the member variable, not the global type.

    There are ways to get around this (e.g., ::Player *GetPlayer) but the best and least confusing fix would be to rename the either the member variable or the type to have a different name.