Robert Carter Mills
Robert Carter Mills

Reputation: 793

How to access class members from a method?

I want to access the engine from inside my eventReceiver object. They are fellow members of the game class, but how do I reach it?

// game.h
class game
{
    public:
        game();
        3dEngine* engine;
        eventReceiver* receiver;
};

// eventReceiver.h
class eventReceiver 
{
    public:
        eventReceiver () {}
        virtual bool OnEvent (const SEvent& event)
        {
            ...
            case QUIT_BUTTON_PRESSED:
>>>             engine->quit();     // how to access engine from here??
                return true;
            ...
        }
};

Should I use 'this' ? I don't understand why receiver can't see the engine.

Upvotes: 0

Views: 124

Answers (3)

Robert Carter Mills
Robert Carter Mills

Reputation: 793

I don't know how elegant this design is, but it works.

I just separated the receiver from the game class and gave its constructor a pointer to the instance of myGame. (Thanks to Paranaix)

class eventReceiver {
    public:
        eventReceiver (game* gameInstance) : gamei(gameInstance)
        virtual bool OnEvent (...) 
            {...
            case QUIT_BUTTON_PRESSED:
                gamei.engine->quitGame();
            ...}
    private:
        game* gamei;
}

int main() {
    game myGame;
    eventReceiver receiver (&myGame);
}

Upvotes: 0

Sebastian Hoffmann
Sebastian Hoffmann

Reputation: 11502

Implement the class as a Singleton and write a getter for the engine property. Accessing code could then look like:

game::getInstance()->getEngine()->quit();

I would recommend you though, that you create a quite() method in the game class itself hiding implementation details and allowing you to handle overall application shutdown and not just of the 3dEngine:

game::getInstance()->quit();

If you dont want to implement the game class as singleton you could also pass a reference/pointer of a game object to the constructor of your event handler:

class CloseButtonHandler : public eventHandler {
    game& game;

public:

    CloseButtonHandler(game& game) : game(game) {
    }

    virtual bool OnEvent(const SEvent& event){
         ...
         game.getEngine()->quit();
    }
}

Upvotes: 1

MSalters
MSalters

Reputation: 180305

The eventReceiver shouldn't know anything about the engine. That's a bad design. There are a few solutions. One reasonable solution is to derive game from eventReceiver since game can clearly receive events. You can then implement the game-specific OnEvent handler in game itself. From there you can call engine->quit.

Upvotes: 0

Related Questions