array of objects, no default constructor

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
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
Not with arrays. You can use std::vector<> instead.

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

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
That would be true if Hand's constructor took the deck by reference (and modified it).
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?
Yes.
Topic archived. No new replies allowed.