0

Let's say I have a class that includes an array of some struct, and a pointer to that array.

struct Box {
    //stuff
};
class Foo {
    private:
        Box *boxPtr     //pointer to an array of Box structs
        int max;        //the size of the partially filled array
        int boxCounter; //the current number of non-NULL elements in the array
    public:
        Foo();                //constructor
        Foo(const Foo &obj);  //copy constructor
        ~Foo();               //destructor
        bool newBoxInsert(Box newBox){
            //adds another Box to my array of Box structs
            boxCounter++;
        }
        //etc
};

and in my int main(), I somehow must create a brand new object of class Foo. I'm going to need to partially fill that array of indeterminate size, whose pointer is boxPtr.

How would I go about initializing that array? Should the constructor do it? Or should I let newBoxInsert handle it?

In either case, how would I achieve that? I'm guessing I would have to dynamically allocate the array. If that's the case, then it's good to have the pointer as a class member... right?

For example, when adding the very first element to my array, should I use

boxCounter = 1;
boxPtr = new Box[boxCounter]; 

then continue on to keep adding elements to the array?

Perhaps this is just better done with vectors. They're much more... flexible (?) when adding elements. Can vectors contain structs as elements?

[/n00b]

1
  • choice of vector or any other STL container depends on what is the ultimate use of that. Commented Jan 26, 2013 at 6:30

1 Answer 1

2
private:
        Box *boxPtr 

replace this by:

private:
        std::vector<Box> mbox;

It saves you all the manual memory management. And you are less likely to go wrong.
Yes, std::vector can contain structs as elements. In fact it is a template class so it can store whatever data type you want.

In C++ if you need dynamic array, the simplest and most obvious choice us std::vector.

Sign up to request clarification or add additional context in comments.

3 Comments

do we have enough info to recommend vector?
@Chubsdad: Yes, a std::vector<Box> is obviously much better than Box *boxptr; which needs to be dynamically allocated as the Q says.
@Chubsdad No, strictly speaking we don't. It could be that the poster is required to guarantee some kind of run-time independent binary compatibility... But, in fact, since he doesn't mention it and his/her class does not seem to equipped for that, I think we can recommend std::vector :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.