C++ how to pass 'this' to pointer reference

user63898 picture user63898 · Sep 1, 2013 · Viewed 13.9k times · Source

i have main class that i like to pass its pointer reference to on of the objects i creating but it gives me error :

Error 1 error C2664: 'GameController::GameController(GameLayer *&)' : cannot convert parameter 1 from 'GameLayer *const ' to 'GameLayer *&'

what i have in the GameLayer ( the main object )

m_pGameController = new GameController(this);

and in the GameController i have this constructor

GameController(GameLayer*& GameLayer)
{
 setGameLayer(gameLayer); // to GameLayer memeber ) 
}

the resone is i need to be able to modify the data in GameLayer from GameController (GUI stuff)

Answer

Uchia Itachi picture Uchia Itachi · Sep 1, 2013

First, the type of this could be GameLayer * const or const GameLayer * const depending upon whether the member function is const or not. But, it is a const pointer.

Having said that, a reference to a pointer type *&ref means indicates that you will be modifying the pointer, the object which it is pointing to.

"Since, this pointer is a constant pointer you cannot assign that to a non-const pointer(GameLayer * p)" in the context of references.

In case of references to pointer, you cannot assign to a reference which will modify the value in this. You cannot assign it to a reference to a non-const pointer(GameLayer *&p), but you can assign a reference to a const pointer i.e. GameLayer *const &p.

So, changing the constructor to GameController(GameLayer * const & gameLayer) should work.
But I don't see any use of it here currently.

And if you're calling from a const member function then this has the type const *const so you will have to change it to GameController(const GameLayer * const & gameLayer).