array of objects, no default constructor

Feb 24, 2011 at 4:48am
Is there a way to create an array of objects when that object has no default constructor?

something like
Hand hands[NUM_PLAYERS](deck)

the constructor for Hand calls for a Deck object, by reference.

If not, do I need to use dynamic memory allocation with a Hand pointer (ie. Hand* hands)?
Last edited on Feb 24, 2011 at 4:49am
Feb 24, 2011 at 4:51am
Yes, but it's quite difficult. Read up on placement new/whatever that other thing is that lets you get uninitialized memory.

EDIT: D'oh, jsmith has a much easier solution...
Last edited on Feb 24, 2011 at 4:52am
Feb 24, 2011 at 4:51am
Not with arrays. You can use std::vector<> instead.

 
std::vector<Hand> hands( NUM_PLAYERS, Hand( deck ) );

Feb 24, 2011 at 6:22am
That does not appear to work precisely as you have indicated, so I used an uninitialized vector and initialized it with a for loop in the constructor. seems to work fine.

declaration
1
2
3
4
5
6
7
8
9
10
class Game
{
private:
	Deck m_deck;
	std::vector<Hand> hands; // line in question here
	
public:

	Game();
};


defintion
1
2
3
4
5
Game::Game()
{
	for(int i = 0; i < NUM_PLAYERS; i++)
		hands.push_back(Hand(m_deck));
}


note: I haven't properly tested this code, but I have checked in the debugger that everything is properly initialized after it is called (ie. Game g)
Last edited on Feb 24, 2011 at 6:24am
Feb 24, 2011 at 2:58pm
That would be true if Hand's constructor took the deck by reference (and modified it).
Feb 24, 2011 at 9:25pm
Yes, Hand's constructor calls the referenced Deck objects Deal member function, which in turn modifies a counter in the Deck object. If this was not the case, the code you provided would work?
Feb 24, 2011 at 10:50pm
Yes.
Topic archived. No new replies allowed.