Sam Sam - 12 days ago 5
C++ Question

Error Passing this pointer as argument to class constructor

I have 3 classes 1) GameStateManager 2) MenuState (Inherits from another class called GameState) 3) GameState

I want to pass this pointer as an argument to MenuState's constructor.

My aim is to get a pointer to GameStateManager object in MenuState for future use.

I am getting errors:

error C2061: syntax error: identifier 'GameStateManager'
error C2664: 'MenuState::MenuState(const MenuState &)': cannot convert argument 1 from 'GameStateManager' to 'const MenuState &'
note: Reason: cannot convert from 'GameStateManager' to 'const MenuState'


GameStateManager.h

#pragma once

#include <vector>
#include <SFML/Graphics.hpp>
#include "MenuState.h"

class GameStateManager {
public:
static const int MENUSTATE = 0;
static const int FIRSTLEVELSTATE = 1;

GameStateManager();

~GameStateManager();
private:
std::vector<GameState*> States;
int currentState;
};


GameStateManager.cpp

GameStateManager::GameStateManager() {
this->currentState = MENUSTATE;
this->States.push_back(new MenuState(*this)); // Error Line. I Think!
}


MenuState.h

#pragma once
#include "GameState.h"
#include "GameStateManager.h"
class MenuState: public GameState{
public:
MenuState(GameStateManager& gsm);
~MenuState();
};


MenuState.cpp

MenuState::MenuState(GameStateManager& gsm){ // Error Line. I Think!
}


GameState.h

#pragma once
#include <SFML/Graphics.hpp>
class GameState {
//Virtual methods are here in this code which are not important for this question
public:
GameState() {}
~GameState() {}
};


Main.cpp

#include <SFML/Graphics.hpp>
#include "GameStateManager.h"

int main(int argc, char** argv) {
GameStateManager gsm;
}

Kai Kai
Answer

Since like the header inclusion conflict in GameStateManager.h and MenuState.h

Use the forward declaration if they are declared as pointers or references:

  1. MenuState::MenuState(class GameStateManager& gsm);
  2. std::vector<class MenuState*> States;

Then, put the line #include "GameStateManager.h" into MenuState.cpp and put the line #include "MenuState.h" into GameStateManager.h would reduce the error.

Comments