tags:

views:

100

answers:

5

I have an array in a class that should hold some instances of other objects. The header file looks like this:

class Document {
private:
    long arraysize;
    long count;
    Row* rows;
public:
    Document();
    ~Document();
}

Then in the constructor I initialize the array like this:

this->rows = new Row[arraysize];

But for some reason this just sets rows to an instance of Row rather than an array of rows. How would I initialize an array of Row objects?

+4  A: 

If arraySize contains a reasonable value at that point you actually get an array. I guess you trust your debugger and the debugger only shows the 0th element (that's how debuggers treat pointers), so you think there's only one object behind that pointer.

sharptooth
+2  A: 

For i in [0;arraysize[, *(this->rows+i) should be an instance of row.

wok
+5  A: 

Both SharpTooth and Wok's answers are correct.

I would add that if you are already struggling at this level you may be better off using a std::vector instead of a built-in array in this case. The vector will handle growing and shrinking transparently.

MadKeithV
+1 for std::vector. And use smart pointers or a `delete_vector` function if you really need pointers (due to polymorphism).
rubenvb
+4  A: 

This should work. One possible "error" would be an incorrect value for arraySize.

However you should better use a std::vector from the standard library for that purpose.

#include <vector>
class Document { 
    // ...
    std::vector<Row> rows;
    // ...
};

and in your constructor:

Document::Document() : rows(arraySize) { // ... }

or

Document::Document() { rows.assign(arraySize, Row()); }
Cedric H.
+1 for std::vector
Viktor Sehr
+1  A: 

What precisely makes you think that rows is only one element? Make certain that you arraysize isn't 1. If it is, you'll get an array of 1 element. Mind you, you must still call delete [] with an array of size 1.

Also, why is arraysize different than count? Using that terminology, you should be making an array of count elements and arraysize should be equal to sizeof(Row) * count.

Also, you specifically ask "How would I initialize an array of Row objects?". Do you mean allocate? If so, that's how you would do so. If you mean initialize, the default constructor of Row will be called on each element of the array when the array is allocated.

Sion Sheevok