Now you need to build a Stock
constructor. Because a Stock
object has three values to be provided from the outside world, you should give the constructor three arguments. (The fourth value, the total_val
member, is calculated from shares
and share_val
, so you don’t have to provide it to the constructor.) Possibly, you may want to provide just the company
member value and set the other values to zero; you can do this by using default arguments (see Chapter 8, “Adventures in Functions.”). Thus, the prototype would look like this:
// constructor prototype with some default arguments
Stock(const string & co, long n = 0, double pr = 0.0);
The first argument is a pointer to the string that is used to initialize the company string
member. The n
and pr
arguments provide values for the shares
and share_val
members. Note that there is no return type. The prototype goes in the public section of the class declaration.
Next, here’s one possible definition for the constructor:
// constructor definition
Stock::Stock(const string & co, long n, double pr)
{
company = co;
if (n < 0)
{
std::cerr << "Number of shares can't be negative; "
<< company << " shares set to 0.
";
shares = 0;
}
else
shares = n;
share_val = pr;
set_tot();
}
This is the same code that the acquire()
function used earlier in this chapter. The difference is that in this case, a program automatically invokes the constructor when it declares an object.
3.128.200.220