Question: A question of C++ code about operator and dynamic memory: In class Ship, assume there is no limit for the array of engines, representing the

A question of C++ code about operator and dynamic memory:

In class Ship, assume there is no limit for the array of engines, representing the engines in the ship.

If the object receives a non-null string for the ship type of 6 characters or less and a positive value for the size of the array, the object accepts the string as the engine type, and sets up the array. Otherwise, the object assumes a safe empty state.

Remember for the operator +=, you will need to:

Dynamically create a new array of desired size (Size should be one more than the old array). (This step will require a second pointer for temporary use).

Copy the old array's contents into the new one.

Copy the object of type engine to the array.

Deallocate the memory of the old array (avoid memory leak).

Adjust pointers so that the new array has the desired name.

So, I don't quite understand "This step will require a second pointer for temporary use" and "Adjust pointers so that the new array has the desired name"

Here's my class and operator+= function:

class Ship { Engine* engine; char* s_type; int engineNo; float distance; public: Ship(); Ship(const char* sh_type, Engine* e, int e_No); ~Ship(); bool empty() const; float calculatePower() const; Ship& operator+=(Engine e); void display() const; void setEmpty(); bool isValid() const; void set(Engine* e, const char* sh_type, int e_No); friend bool operator==(const Ship&, const Ship&); };

Ship& Ship::operator+=(Engine e) { if (s_type == nullptr || s_type[0] == '\0') { cout<<"The ship doesn't have a type! Engine cannot be added!"<

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!