Sam Sam - 1 year ago 63
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'


#pragma once

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

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


std::vector<GameState*> States;
int currentState;


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


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


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


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


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

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

Kai Kai
Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download