[gameprogrammer] Re: dynamic array allocation in a class?

G'day Justin and all,

On Wed, 09 Jun 2004 11:26:33 -0400, "Justin Coleman" <JMCOLE@xxxxxxxxx>
said:
> What I'd like to do, now that I have code to
> save the generated coordinates to a file, is to make the class member
> arrays dynamically allocated, so I can load from a file as well. I'd
> like to make several different resolution files, so I can test my
> program on lower end machines as well. Can anyone give me a push in 
> the right direction?

Sounds like a plan.

> Here's the structure of what I have now:
> 
> class cSphere {
> public:
> 
>       struct vertex {
>       GLfloat x, y, z;
>       } verts[19][19];
> 
>       struct texcoord {
>       GLfloat u, v;
>       } coords[19][19];
> 
>       struct normal {
>       GLfloat x, y, z;
>       } face_normals[648];
> 
>       struct tri {
>       GLuint a_col, a_row, b_col, b_row, c_col, c_row;
>       } faces[648];
> 
>       int num_faces;
> 
>       cSphere::cSphere();
>       int cSphere::Generate(int rows, int columns);
>       int cSphere::Save(char *filename);
>       int cSphere::Load(char *filename);
>       void cSphere::Render(void);
> };

Well, this code looks a lot like C code that's been shoehorned into a
class, so there may be a better way to go.

> I want to have the Load and Generate functions allocate the
> vertex/normal/face arrays when they run, rather than having them
> statically defined as part of the base class. Is there a way to do 
> this without using a linked list of individual vertices, etc?

All right, the best way to do this is probably to use a STL vector, as
that's dynamically resizable and can give you some array bounds overflow
protection.  It should also definitely be fast enough for your purposes. 
The downside is that it won't be directly 2-dimensional, but this is
barely a problem.

So you'd do something like this:

class cSphere
{
  std::vector<vertex> mVertices;
}

int cSphere::Load(char* filename)
{
  int numVertices = loadNumVertices();
  mVertices.resize(numVertices);
  for (int i = 0; i < numVertices; ++i)
    mVertices[i] = loadVertex();
}

And extend that across everything else.  The key functions are resize (to
set the size of the vector) and operator[] (which accesses a value).  As
I said, it's not directly two dimensional - in order to get that
functionality you need to multiply the two dimensions together.  Then,
when accessing a value, it's at index (y*width)+x, where x and y are the
two coordinates and width is the width of one line of the array.

If you're using the C++ STL for the first time, it's a good idea to read
about it.  Stroustrup's book, 'The C++ Programming Language' is good, as
is Josuttis' 'The Standard Template Library' (I think that's the title).

Hope that helps.

Dave.
-- 
  Dave Slutzkin
  Melbourne, Australia
  daveslutzkin@xxxxxxxxxxx


---------------------
To unsubscribe go to http://gameprogrammer.com/mailinglist.html


Other related posts: