Question: Rewrite the Stock class, as described in Listings 10.7 and 10.8 in Chapter 10 so that it uses dynamically allocated memory directly instead of using
Rewrite the Stock class, as described in Listings 10.7 and 10.8 in Chapter 10 so that it uses dynamically allocated memory directly instead of using string class objects to hold the stock names. Also replace the show() member function with an overloaded operator

Here is the output from the program in Listing 10.9:
Stock holdings:
Company: NanoSmart Shares: 12
Share Price: $20.000 Total Worth: $240.00
Company: Boffo Objects Shares: 200
Share Price: $2.000 Total Worth: $400.00
Company: Monolithic Obelisks Shares: 130
Share Price: $3.250 Total Worth: $422.50
Company: Fleep Enterprises Shares: 60
Share Price: $6.500 Total Worth: $390.00
Most valuable holding:
Company: Monolithic Obelisks Shares: 130
Share Price: $3.250 Total Worth: $422.50
One thing to note about Listing 10.9 is that most of the work goes into designing the class. When that’s done, writing the program itself is rather simple. Incidentally, knowing about the this pointer makes it easier to see how C++ works under the skin. For example, the original Unix implementation used a C++ front-end cfront that converted C++ programs to C programs. To handle method definitions, all it had to do is convert a C++ method definition like
void Stock::show() const
{
cout }
to the following C-style definition:
void show(const Stock * this)
{
cout company
shares share_val
total_val }
That is, it converted a Stock:: qualifier to a function argument that is a pointer to Stock and then uses the pointer to access class members.
Similarly, the front end converted function calls like
top.show();
to this:
show(&top);
In this fashion, the this pointer is assigned the address of the invoking object. (The actual details might be more involved.)
Listing 10.9 usestok2.cpp // usestok2.cpp using the stock class // compile with stock20.cpp #include #include "stock20.h" const int STKS = 4; int main() { // create an array of initialized objects stock stocks [STKS] = { } Stock ("NanoSmart", 12, 20.0), Stock ("Boffo Objects", 200, 2.0), stock ("Monolithic Obelisks", 130, 3.25), Stock ("Fleep Enterprises", 60, 6.5) }; std::cout < < "Stock holdings: "; int st; for (st = 0; st < STKS; st++) stocks [st].show(); // set pointer to first element const Stock* top = &stocks [0]; for (st = 1; st < STKS; st++) top &top->topval (stocks [st]); // now top points to the most valuable holding std::cout < < " Most valuable holding: "; top->show(); return 0;
Step by Step Solution
3.38 Rating (157 Votes )
There are 3 Steps involved in it
include include stock20h const int STKS 4 int main create an array of initialized objects Stock ... View full answer
Get step-by-step solutions from verified subject matter experts
