Marco Berrocal
Marco Berrocal

Reputation: 362

How can I pass the same object to another method of another object?

Say I have an object of type Game instantiated somewhere, and I have another class called Writer where I want to save it....

So in Writer class I have....

void gameWriter(Game g) {
  some wonderful logic here....

}

And inside Game, I want to call gameWriter... so I have a method that goes like this (inside Game)

void Game::saveGameDetails() {

    Writer w;
    w.gameWriter(this);  //this is where it fails...

}

How can I call gameWriter within Game using that same object I am currently using?

Upvotes: 0

Views: 30

Answers (3)

C-Kennelly
C-Kennelly

Reputation: 68

Not sure if this will work, but try declaring Writer() as a static class. Then, you don't need to instantiate it in your instance of Game, just call Writer.Save(this);

I suggest this because I am guessing the error is occurring when you pass an instance of game to the instance of gameWriter(), but since w is inside of Game, things might get weird.

Upvotes: 0

R Sahu
R Sahu

Reputation: 206737

To be syntactically correct, you need to use:

w.gameWriter(*this);

I would further suggest the use of Game const& or Game& as the argument type in gameWriter.

void gameWriter(Game const& g) { ... }

Then you will save on the cost of creating a copy of the Game.

Upvotes: 1

Alex Lop.
Alex Lop.

Reputation: 6875

It fails because you pass a pointer this while according to the signature of gameWriter, it expects the object itself. Try this

void Game::saveGameDetails()
{
    Writer w;
    w.gameWriter(*this);  
}

Upvotes: 0

Related Questions