Rewrite the Stock class, as described in Listings 10.7 and 10.8 in Chapter 10 so that it

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 string class objects to hold the stock names. Also replace the show() member function with an overloaded operator<<() definition. Test the new definition program in Listing 10.9.

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 << "Company: " << company
<< " Shares: " << shares << ‘\n’
<< " Share Price: $" << share_val
<< " Total Worth: $" << total_val << ‘\n’;
}
to the following C-style definition:
void show(const Stock * this)
{
cout << "Company: " << this->company
<< " Shares: " << this->shares << ‘\n’
<< " Share Price: $" << this->share_val
<< " Total Worth: $" << this->total_val << ‘\n’;
}

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.)

Fantastic news! We've Found the answer you've been seeking!

Step by Step Answer:

Related Book For  answer-question

C++ Primer Plus

ISBN: 9780321776402

6th Edition

Authors: Stephen Prata

Question Posted: