C++/need a little help with this program
Expert: Zlatko - 11/1/2010
QuestionHi Zlatko,
Thanks for the polynomial help last time. Now here's a stock
program (see code below), Now, I've made instantiated the
buyprice as 69.34 and the numshares as 150. When calculating
total cost, I would be using numshares * buyprice and should
get 10401. Why am I not seeing that when I run this program,
where did I go wrong?
Also, I didn't do any of the formatting yet so sorry if the
output seem little wierd somehow (the printing out of the
dollar sign and the two digits after decimal place as money
amounts are usually written -- US dollars at least)
#include <iostream>
#include <iostream>
#include <string>
using namespace std;
class Stock
{
public:
Stock (char *n = " ", float = 0.0, float = 0.0,
float = 0.0, float = 0.0, float = 0.0, float = 0.0);
~Stock();
void printData();
void stockRecalc(float);
private:
char name[30];
float numshares, buyprice, currentprice, totalcost,
currentvalue, profit;
};
Stock :: Stock(char*n, float ns, float bp, float cp, float
totalcost, float cvlue, float profit)
{
strcpy(name, n);
numshares = ns;
buyprice = bp;
currentprice = cp;
totalcost = numshares * buyprice;
currentvalue = numshares * currentprice;
profit = currentvalue - totalcost;
}
Stock :: ~Stock()
{
cout << name << " is destroyed" << endl;
}
void Stock :: stockRecalc(float newcprice)
{
currentprice += newcprice;
currentvalue = numshares * currentprice;
profit = currentvalue - totalcost;
}
void Stock :: printData()
{
cout << name << "\n" ;
cout << numshares << "\n" ;
cout << buyprice << "\n";
cout << currentprice << "\n";
cout << totalcost << "\n";
cout << currentvalue << "\n";
cout << profit << "\n";
}
int main()
{
Stock s("Joe's Technology", 150, 69.34, 77.55);
s.printData();
float newcprice;
cout << "\n" << "enter the change in the current
price: ";
cin >> newcprice;
s.stockRecalc(newcprice);
s.printData();
cout << endl << endl;
return 0;
}
AnswerHi Mike. You've fallen into a common trap.
Your Stock class has a float totalcost data member, and your Stock constructor has a totalcost parameter.
In the constructor, the totalcost parameters hides the totalcost data member, so when you write
totalcost = numshares * currentprice, you are actually changing the value of the parameter, not the value of the data member. One solution is to write it like this:
this->totalcost = numshare * currentprice.
That ensures that the calculation is assigned to the data member. Many programmers prefer to prefix all data member names with an 'm' to avoid any confusion.
Looks like your assignments are coming in fast. What school do you go to?
Bye for now.