1

I'm currently learning C++, but It doesn't works like I expected. I made some classes for a BowlingGame (just something text-based) and that works well. But now I want to pass an object of a BowlingGame to another class, called ScoreCalculator.

The header file looks like:

#ifndef SCORECALCULATOR_H
#define SCORECALCULATOR_H
#include "BowlingGame.h"

class ScoreCalculator {
private:
    BowlingGame * game;
public:
    //constructor
    ScoreCalculator(const BowlingGame &game);

    //setters
    void setGame(const BowlingGame &game);
};

#endif // SCORECALCULATOR_H

And the implementation looks like:

#include "ScoreCalculator.h"
#include "BowlingGame.h"
#include <iostream>

using namespace std;

ScoreCalculator::ScoreCalculator(const BowlingGame &game) {
    setGame(game);
}

void ScoreCalculator::setGame(const BowlingGame &gamse) {
    //* game = gamse; this fails
    //cout << gamse.getLastFrameNummer(); this works
}

I would like to save the 'BowlingGame object' in the instance var game, but for some reason my console application crashes. I've no idea what I'm doing wrong. The failure is in the rule: * game = gamse; I looked up some examples on the internet, but can't find a solution.

2 Answers2

1

Your problem here is that you aren't allocating your pointer. Why don't you just define "game" as BowlingGame game; in the header? This way your other code will just work. It will mean that the BowlingGame structure is "copied" into the one in the class but this sounds to be what you are after.

Goz
  • 61,365
  • 24
  • 124
  • 204
  • +1 for a good answer, but I think a little code sample would help the questioner understand. – john May 04 '13 at 15:39
-1
//* game = gamse; this fails

you haven't allocated anything for game. It is just a pointer not pointing to anything valid yet. You have to create a new Game object for it to point to.

Do it like this

game = new Game(gamse);

Assuming Game has an accessible copy constructor.

Also Don't forget to delete game in your destructor or earlier if you don't need it any more. Or even better use a smart pointer for `game.

Community
  • 1
  • 1
stardust
  • 5,918
  • 1
  • 18
  • 20
  • And don't forget to free the game on destruction of the object! smart_ptr perhaps? – Goz May 04 '13 at 14:38