Instantiate A Singleton Object

Hello I am trying to create a singleton object for class I cant seem to create a instances correctly. I have seen very few examples of this in c++. My book is in Java and the few c++ examples I found don't seem to work. There is a lot of code in my program so I will just post the two relevant classes please let me know if you need more. Thanks.

Here is the pastebin page sorry I could not figure out how to create a link.

 
http://pastebin.com/2mbw1i4V 
There is rarely a need to use new in C++, and singletons are no exception: just return a reference:

1
2
3
4
5
6
7
    class GameBoard
    {
    public:
        static GameBoard& instance() {
            static GameBoard gb;
            return gb;
        }


then later in code, you can use
GameBoard::instance().get_contents_of_chosen_cell(Location(x,y))
or, if you want to save typing, name that reference:
1
2
3
GameBoard& r = GameBoard::instance();
...
r.get_contents_of_chosen_cell(Location(x,y))


Incidentally, why does it need to be a singleton? I don't see why there can't be more than one game board in existence.
Last edited on
Thanks for the help.Thhis is homework for a design patterns class.
sorry I could not figure out how to create a link.

Links only work inside [code][/code] tags when commented

// http://pastebin.com/2mbw1i4V

or you can use [output][/output] tags


or [quote][/quote] tags

http://pastebin.com/2mbw1i4V

or no tags

http://pastebin.com/2mbw1i4V

Andy



Last edited on
Thanks man.
Another question this object is a two dim array and I need to populate it in the ctor how do I do that with a call to a static function.
1
2
3
4
5
6
7
GameBoard::GameBoard( )   /// populates gameBoard with empty organisms
{
	for(int i =0; i < ROWS; i++)
	     for(int j =0; j < COLUMNS; j++)
			m_gameboard[i][j] = Organism(Location(i, j),'*'); //<-- ??
}
Last edited on
That constructor is fine as-is. it will be called by instance() the first time it is called by user code
Yea thanks I think miss understood what was going on here. Thanks everyone.
Topic archived. No new replies allowed.