Click to See Complete Forum and Search --> : arrays of objects
jmiller
Nov 19th, 2002, 06:50 PM
I want to declare a global array of objects, but i don't know how many objects there will be until later in the program. how would i do this?
thanks
kedaman
Nov 19th, 2002, 08:09 PM
you declare a pointer to the object.
to allocate an deallocate memory dynamically you use new and delete.
ex
obj* g_myobjarray;
..
g_myobjarray=new obj[x];
..
delete[] g_myobjarray;
CornedBee
Nov 20th, 2002, 04:47 AM
Or you declare an STL vector, which is easier to use.
jmiller
Nov 20th, 2002, 08:28 PM
say i do something like this:
Obj *myObj;
myObj = new Obj[10];
Now, myObj is a pointer right? So if I wanted to pass the array byref to a function, would i have to pass the memory address of the pointer myObj to a function that accepted the value as another pointer? Like:
void blah(Obj *pointer) {}
blah(&myObj)
or could I just pass the pointer myObj and not the mem address? Also, is there any way for 'blah' to tell the upper bound of the array that was passed? What is the correct argument syntax for passing an array?
thanks
jmiller
kedaman
Nov 21st, 2002, 04:45 AM
I suggest you do as CB suggested and have a look at the vector if you want a fast and easy solution, if you're practicing C++ arrays, pointers and references can be very useful to understand
myObj is a pointer to the first object in the array, if you want to reassign or resize the array you'd better pass the pointer by reference, Obj *&pointer, and when you declare a reference, you don't have to use the addressof operator, so
void blah(Obj *&pointer) {}
..
blah(myObj);
if you only want to change or access of the array elements, you could just pass the pointer, but you cannot change the pointer (you can but only in this scope.)
void blah(Obj *pointer) {}
..
blah(myObj);
The size of the array has to be passed as well in a separate variable, if you intend to resize it. Remember for each new you have to use delete, and be cautious to new and delete in separate scopes, you'll easily end up with memory leaks, its not considered as good programming to do so.
vbforums.com
Copyright Internet.com Inc., All Rights Reserved.