Const_cast on a this pointer - would I get told off by other C++ coders for doing this?

Posted by BeeBand on Stack Overflow See other posts from Stack Overflow or by BeeBand
Published on 2011-01-05T10:51:30Z Indexed on 2011/01/05 10:53 UTC
Read the original article Hit count: 196

Filed under:
|

I have a class Game e.g.

class Game
{
    public:
        InitObjects();
        ...
};

And I have another class Grid, that needs to be initialised with a non-const reference to that Game object. ( A Grid object needs to call functions that can update a Game object ).

class Grid
{
    public:
        Grid(Game & g):
            game(g){}
        ...
    private:
        Game & game;
        ...
};

The Game object is responsible for initialising the Grid. I did this:

void Game::InitObjects()
{
    grid = new Grid(*(const_cast<Game*>(this)) );
}

grid is not a member of a Game - it's a global ( argh - i know... I don't mind making it a member, but I have the same problem right? ). Can some seasoned C++ folk tell me if this odd looking const_cast is acceptable?

© Stack Overflow or respective owner

Related posts about c++

Related posts about const