Reputation: 57
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 !
Upvotes: 0
Views: 1151
Reputation: 73376
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; }
Upvotes: 2