0

I'm working on a C++ project which basically uses a couple of classes to simulate a retail environment; so far everything has gone smoothly, but I haven't been using C++ for very long and I'm a little stumped on how this array is supposed to work.

//Customer.h
private:
    std::array< CustomerOrder *, 3 > orderList;

Basically, the array is declared in the Customer.h file as private, but the Customer.h and Customer.cpp files also provide a method

addOrder(CustomerOrder *c)

for adding CustomerOrder pointers(CustomerOrder being another class) to the array. From my experience, the logic for the method is pretty straightforward: Use a for loop to find the first index containing a null pointer, then insert a pointer into that index.

The issue is, that involves first initializing the array to null pointers, and I'm not sure how or in which file I should do this. Since the array is private, I would assume I have to initialize it in the .h file using something along the lines of

for(size_t i = 0; i < orderList.size(); ++i)
    orderlist[i] = nullptr;

or

orderlist[3] = {nullptr}

Can I/Do I have to do this in a .h file? And is there a more trustable way to initialize the array?

For reference, I'm using the C++11 standard, if that makes any difference.

2 Answers 2

1

If this data member is private then it can be initialized either in a constructor or in some member function that will initialize it.

To set all elements of the array to nullptr you can use member function fill of class std::array.

For example

orderlist.fill( nullptr );
Sign up to request clarification or add additional context in comments.

Comments

1

Use a constructor, and executable code isn´t supposed to be in a h-file.
And: Don´t do orderlist[3] = {nullptr} on a 3-sized array.
It only has the indizes 0,1,2. The loop is far better.

Comments

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.