Note that there are some explanatory texts on larger screens.

plurals
  1. PO"No known conversion" from const when passing "this" as a parameter
    text
    copied!<p>I am currently making a game which utilizes a state stack manager which keeps track of all the different game states, like the main menu.</p> <p>However, I have encountered a problem which I can't seem to solve.</p> <p>This is the state class, stripped down to only contain the offending code:</p> <pre class="lang-c prettyprint-override"><code>class StateManager; namespace first { namespace second { class State { friend class StateManager; protected: /** * Associates the state with the specified state manager instance. * @param stateManager The instance to associate this state with */ void associateWithManager(StateManager *stateManager) { mStateManager = stateManager; } private: StateManager *mStateManager; }; } // second } // first </code></pre> <p>The following is the state manager, also stripped down:</p> <pre class="lang-c prettyprint-override"><code>namespace first { namespace second { class StateManager { public: /** * Adds a state to the stack. * @param state The state to add */ State &amp;add(State &amp;state) { state.associateWithManager(this); return state; } }; } // second } // first </code></pre> <p>When I try to compile this, I get the following error (line numbers are a bit off, since I have include guards, etc.):</p> <pre><code>src/StateManager.cc: In member function 'State&amp; StateManager::add(State&amp;)': src/StateManager.cc:7:34: error: no matching function for call to 'State::associateWithManager(StateManager* const)' src/StateManager.cc:7:34: note: candidate is: In file included from ./include/StateManager.h:4:0, from src/StateManager.cc:1: ./include/State.h:29:10: note: void State::associateWithManager(StateManager*) ./include/State.h:29:10: note: no known conversion for argument 1 from 'StateManager* const' to 'StateManager*' </code></pre> <p>Apparently, the <code>this</code> pointer is treated like a const pointer, even though I don't use the <code>const</code> keyword on the <code>add</code> method. I'm not sure exactly what is going on here. Is the <code>this</code> pointer always <code>const</code>? I'm pretty sure I've used it this way in the past with no problems though.</p> <p>Also, is the way I'm going about this the 'correct' way? Or is there a better solution when it comes to letting the state know about the manager? Perhaps using a singleton, but I'm not really a big fan of that.</p> <p><strong>EDIT:</strong> I now realize that the forward declaration outside the namespaces was the reason for this. Should I accept Mike's answer, since it helped me come to this conclusion? Or should I post my own?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload