How to fix Unhandled exception thrown

Solution for How to fix Unhandled exception thrown
is Given Below:

enter image description here

enter image description here

how to fix it,When I write the main function, and call to the set method, show me Unhandled exception. and show me the variable unable to read memory.

shipContainer* shipContainer1[6];

That’s not an array of shipContainer objects. It’s an array of 6 pointers to shipContainer objects, which are actually stored somewhere else in memory.

But then the array is left uninitialized and the individual entries are not pointing anywhere. So when you try working with them, it crashes or exhibits some other undefined behavior.

If you wanted an array of 6 shipContainer objects instead, right there on the stack, do something like this:

shipContainer shipContainer1[6];
shipContainer1[0].setContainerID(100);

I.e. 1) no asterisk on the first line, and 2) . instead of -> on the subsequent ones.


Alternatively, if you want an array of pointers, you will need to initialize it to point to some valid constructed objects first, e.g.

for (int i = 0; i < 6; i++)
    shipContainer1[i] = new shipContainer();

Note that the objects should then be also destructed somewhere later with a delete statement. Or just use a smart pointer. Or a full-fledged STL structure like std::vector<>. There is no need to handle all this by hand in C++.

As the other answer states, each element of the array is a pointer, which needs to be initialized. Since you asked, I’ll show how to initialize each member, however, I will preface by stating that this is not recommended in modern c++.

shipContainer* shipContainer1[6];
for ( size_t idx = 0; idx < 6; ++idx) 
    shipContainer1[idx] = new shipContainer;

shipContainer1[0]->setContainerID(100);

When done with the container, don’t forget to delete.

for ( size_t idx = 0; idx < 6; ++idx) 
    delete shipContainer1[idx];