Question: // This program illustrates the use of copy constructors. C++ #include #include using namespace std; class Inventory // class declaration with member functions defined in-line
// This program illustrates the use of copy constructors. C++
#include
#include
using namespace std;
class Inventory // class declaration with member functions defined in-line
{
private
char *description;
double price;
public:
Inventory() // default constructor
{ price = 0;
description = new char[6];
strcpy(description, "empty");
}
Inventory(char* d, double p) // constructor
{ description = new char[strlen(d) + 1]; // Get needed amount of memory
// to hold the description.
strcpy(description, d);
price = p;
}
~Inventory()
{ delete[] description; } // Use destructor to free the memory
// allocated for the dynamic variable.
const char* getDescription()
{ return description; }
double getPrice()
{ return price; }
void setDescription(char* d) // "Assumes" dynamic description
{ strcpy(description, d); // variable has enough memory to hold
} // the new string.
void setPrice(double p)
{ price = p; }
};
int main()
{ Inventory toolOne("screwdriver", 2.99);
// Fill in the code to create a new Inventory object named
// toolTwo that is initialized with the values of toolOne.
cout << fixed << setprecision(2) << showpoint;
cout << "toolOne: " << toolOne.getDescription() << " $"
<< toolOne.getPrice() << endl;
cout << "toolTwo: " << toolTwo.getDescription() << " $"
<< toolTwo.getPrice() << endl << endl;
// Fill in the code to change toolTwo's description to "electric screwdriver"
cout << "toolOne: " << toolOne.getDescription() << " $"
<< toolOne.getPrice() << endl;
cout << "toolTwo: " << toolTwo.getDescription() << " $"
<< toolTwo.getPrice() << endl << endl;
return 0;
}
Exercise 1: Fill in the code as indicated in bold type to complete program. Run and observe the
output.
Exercise 2: This may cause your program to abort on some systems. If it ran and produced output,
rather than aborting, explain why toolOnes description changed.
Exercise 3: Write a copy constructor, and place it in the Inventory declaration with the other
constructors. Rerun the program. Now, when toolTwos description is changed, toolOne should not
be affected.
Exercise 4: The setDescription member function, assumes there has been enough memory
allocated for the description to hold any new string being passed to it. This is not a safe assumption.
Rewrite the code in this function to free the current memory pointed to by the description pointer
and allocate the right amount of memory for the new string being passed to the function. Rerun your
program with the new function to make sure it still works correctly.
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
