• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C++ : creating dynamic classes ?

Hmongkeysauce

Senior member
lets say i have a 'player' class defined. in the main, i ask the user to input the amount of players that are going to play the game. he/she enters a number. then, i would need to create that many instances of the 'player' class. whats the best way to go about doing this ? thanks in advance.
 
I think I would do it as I would an array.
(keep in mind, I'm a non-OOP programmer starting to venture into OOP):

Player *player = new Player[num_players];

After that, you simply index into the array:

player[p_idx].moveto (x_lox, y_loc);

I think this is how it would be, but I'm just starting to get back into OOP. Remember to check it for success.

Some of the old hands can correct me if I'm wrong.

If this is one time allocation, I'd leave it as it. If you'll be doing multiple allocations, you'll want to look into block allocations and garbage collection and overload the new operator.
 
if you dont want to have to reallocate new a lot of times, just use something like the STL and use list or something (if its not like 8 million players anyway).

i'm sure that would b efine. list basically would be like making your own linked list class and doing all the operations to add nodes and such, just already made for you with the STL



EDIT...

opps i think i read that wrong. yeah the last guy is right just use an array if you know the amount before hand. you cant create a normal array with a variable as the index part...

so you'd do something like


player * blah= new player[number of players];

im not really sure what the last poster is talking about with move to.. but to access each guy you'd just go something like.


blah[index] and to access member functions do something like blah[2].functionImade();
 
Originally posted by: hans007
im not really sure what the last poster is talking about with move to.. but to access each guy you'd just go something like.

It was intended to show how you'd reference a member function via an indexed class. It had no bearing on what the OP is doing, it was just an example.


 
Create an array (or whatever STL object you'd rather use instead) to hold the references to the players. Use a loop to create the individual players and place them in the array (or whatever container you use).

It's been awhile since I've written any C++ so the syntax here might be a little messed up but you should get the general idea.

Example:

// do input here, so the variable "numPlayers" contains the number of players (int)

// array that holds the game's players
Player *gamePlayers = new Player[numPlayers];

// create the player objects and insert into array
for (int i = 0; i < numPlayers; i += 1) {
......Player *currentPlayer = new Player(....); // call constructor with whatever arguments (if any)
......gamePlayers[ i] = currentPlayer;
}


Jesus the f'ing Attach Code feature needs to be fixed. :roll:
 
I'll just reiterate that to dynamically create the desired number of objects, you should do so on the heap (instead of the stack) using the new/delete operators.

SomeClass* bunchOfObjects = new SomeClass[n];

... do something interesting with the bunchOfObjects

delete [] players;

Don't forget the brackets when you delete the objects, or you will destruct just the first object in the array and the memory allocated for the rest of the array will be leaked.


In C you can do similar dynamic allocation with malloc and free. Also, the "C99" standard (not widely implemented) now supports variable-length arrays!
 
Originally posted by: clamum
Create an array (or whatever STL object you'd rather use instead) to hold the references to the players. Use a loop to create the individual players and place them in the array (or whatever container you use).

It's been awhile since I've written any C++ so the syntax here might be a little messed up but you should get the general idea.

Example:

// do input here, so the variable "numPlayers" contains the number of players (int)

// array that holds the game's players
Player *gamePlayers = new Player[numPlayers];

// create the player objects and insert into array
for (int i = 0; i < numPlayers; i += 1) {
......Player *currentPlayer = new Player(....); // call constructor with whatever arguments (if any)
......gamePlayers[ i] = currentPlayer;

}


Jesus the f'ing Attach Code feature needs to be fixed. :roll:

nope, can't do that ... unless you Player **gamePlayers = new Player*[numPlayers];
 
A different answer for hte heck of it..

Just give the player class a stitic getHead() method and a getNext() method. Do a linked list 😉
 
Originally posted by: HigherGround

nope, can't do that ... unless you Player **gamePlayers = new Player*[numPlayers];

That's how you allocate for the pointer to the pointers in a dynamic multi-dimensional array in C++?
 
Originally posted by: aCynic2
Originally posted by: HigherGround

nope, can't do that ... unless you Player **gamePlayers = new Player*[numPlayers];

That's how you allocate for the pointer to the pointers in a dynamic multi-dimensional array in C++?

what's with the question mark?
 
Originally posted by: HigherGround
Originally posted by: aCynic2
Originally posted by: HigherGround

nope, can't do that ... unless you Player **gamePlayers = new Player*[numPlayers];

That's how you allocate for the pointer to the pointers in a dynamic multi-dimensional array in C++?

what's with the question mark?

I should have rephrased:

Is that how you allocate for the pointers to pointers in a dynamic multi-dimensional array in C++?

I do it like this in C:

if ((mdl->surface_list = (SURFACE **)realloc ( mdl->surface_list, (mdl->num_surfaces * 2) * sizeof (SURFACE *))) == NULL)
{
// error handler here
}

I'm curious if the method you posted is the proper way in C++.

I think as my first C++ project, I'm going to port fisix over from non-OOP C to OOP C++, with the addition of a block allocation methodology. Fisix being the 3D object tracer that generates physical data.
 
Originally posted by: aCynic2
Originally posted by: HigherGround
Originally posted by: aCynic2
Originally posted by: HigherGround

nope, can't do that ... unless you Player **gamePlayers = new Player*[numPlayers];

That's how you allocate for the pointer to the pointers in a dynamic multi-dimensional array in C++?

what's with the question mark?

I should have rephrased:

Is that how you allocate for the pointers to pointers in a dynamic multi-dimensional array in C++?

I do it like this in C:

if ((mdl->surface_list = (SURFACE **)realloc ( mdl->surface_list, (mdl->num_surfaces * 2) * sizeof (SURFACE *))) == NULL)
{
// error handler here
}

I'm curious if the method you posted is the proper way in C++.

I think as my first C++ project, I'm going to port fisix over from non-OOP C to OOP C++. Fisix being the 3D object tracer that generates physical data.

I think it's more OO when compared to going through a series of mallocs/sizeofs/explicit casts. A lot of people stick to reallocs because it's so much cooler to fall back on old school one liners instead of going with the check if need to realloc, alloc temp array, copy contents, delete old array, assignment. However C++ gives you ability to skip all that with template classes. For example here's a simple mem class along with the dynarray class, which does the reallocs for you.

template <typename T>
class Memory {
public:

static T* alloc(int size) {
static int s = 0;
return realloc(NULL, s, size);
}

static T* realloc(T* t, int& current_size, int new_size) {
T* result = new T[new_size];
if(result != NULL) {
if(t != NULL && current_size > 0) {
for(int j =0; j<current_size; j++) {
result[j] = t[j];
}
delete [] t;
}
current_size = new_size;
}
else {
current_size = 0;
}
return result;
}
};

template <typename T>
class Array {
private:
T* _array;
int _position;
int _size;

void grow(int factor = 2) {
_array = Memory<T>::realloc(_array, _size, _size * factor);
}

bool at_limit() {
return _position == _size - 1;
}

public:
Array(int size) {
_array = Memory<T>::alloc(size);
_size = size;
_position = 0;
}

virtual ~Array() {
for(int j = 0; j < _position; j++)
delete _array[j];
delete [] _array;
}

void append(T t) {
if(at_limit())
grow();
_array[_position++] = t;
}
};

int main() {

Array<A*> array(10);
for(int j = 0; j < 21; j++)
array.append(new A());

return 0;
}

EDIT: is 'attach code' function completely broken, or is it just me?
 
Originally posted by: programmer
"C99" standard (not widely implemented) now supports variable-length arrays!
Really? As in:

func(int n)
{
char array[n];
...
}
?

Does it use the stack? That would be much cleaner than alloca() which wasn't available everywhere.

---

Or are you referring to:

int n = 3;
char array[n];

func(char* a, int asize)
{
...
}

func(array, n);
?
 
Back
Top