0

I have a class, Game, which has in argument a std::vector of another class, Case. In this class Case, I have a function which tells me when we click on it. And I want to send a signal to my object Game, which owns the Cases, when a Case is pressed. In game.h :

class Game
{
public:
    Game();
    void doSomething();

private:
    std::vector<Case> board;
};

And in case.h :

class Case
{
    public:
        Case(Game &g);
        void functionWhichIsCalledWhenCaseIsPressed();
    private:
        Game game;
};

So, when the functionWhichIsCalledWhenCaseIsPressed() is called, I want to call the function doSomething(). EDIT :

I tried, but I also need to create a case out of the vector... Actually, I have a Case c; in my Game.h... And I cannot initialize it... I tried c = Game(*this); But I have an error :

error: object of type 'Case' cannot be assigned because its copy assignment operator is implicitly delete

EDIT : Thank you, it's done !

GtN
  • 57
  • 4
  • 1
    One way to do this would be to have each Case store a pointer back to the Game object. Would that resolve your issue? – templatetypedef Mar 19 '19 at 20:50
  • 4
    I would go the other way - have `Case` hold a function pointer or `std::function` that it can call when needed, and then have `Game` assign `doSomething()` to that when it populates the `std::vector`. – Remy Lebeau Mar 19 '19 at 21:02
  • check out [observer pattern](https://en.wikipedia.org/wiki/Observer_pattern) – adrtam Mar 19 '19 at 21:05

1 Answers1

2

For this to happen, you need to enable a navigation from a Case to its owning Game. One way to do this is to keep in each Case a reference or a pointer to the owner, and initalize this reference at construction:

class Game; 
class Case
{
    public:
        Case(Game& x);
        void functionWhichIsCalledWhenCaseIsPressed();
    private: 
        Game &game;  // <<<<-------------- reference to owner
};

With these prerequisite, you can easily invoke the parent's function:

Case::Case(Game& x) : game(x){
}
void Case::functionWhichIsCalledWhenCaseIsPressed() {
    cout<<"Clicked"<<endl; 
    game.doSomething();    //<<<===== invoke the function of the owner
}

This requires that the game initializes the board and provides the right parameters to the constructor:

Game::Game() {
    for (int i=0; i<10; i++)
        board.push_back(Case(*this));
}
void Game::doSomething() { cout<<"click on game"<<endl; }

Online demo

Christophe
  • 68,716
  • 7
  • 72
  • 138