So I'm trying to subtract wholeParts which represent a currency like dollar and fracParts which represents the coin like cents. I've tried doing this a couple ways but keep getting an incorrect answer like $5.00 - $1.25 = $4.25 instead of $3.75. This is the operator from my currency class:
Currency operator-(const Currency& c)
{
Currency currency;
int diff = (this->wholeParts * 100 + this->fracParts) - (c.wholeParts *100 + c.fracParts);
Currency local(diff);
return local;
// currency.wholeParts = this->wholeParts - c.wholeParts;
//
// if(fracParts == 0)
// {
// currency.wholeParts = this->wholeParts-c.fracParts;
// }
// else
// {
// currency.fracParts = this->fracParts - c.fracParts;
// }
// return currency;
}
Here's my dollar class:
class Dollar: public Currency
{
public:
Dollar(int w = 0, int f = 0)
{
currencyNote = "dollars";
currencyCoin = "cents";
fracParts = f;
wholeParts = w;
}
};
How I implemented the operator in main:
int main()
{
Dollar d1(1,25), d2(5,0);
Currency d4 = *new Dollar(0,0);
cout<<d4<<endl;
return 0;
}
I would store the value of a currency in it's equivalent of "cents" and always work internally with that, only converting to/from "whole parts" and "fractional parts" on output/input. Then the math is simple.
You probably need to post the whole shebang since the error could be in the function that converts diff to Currency, for instance. It doesn't seem to be in operator-, per se.
And remember to wrap your code in code tags when posting code.
Don't do this! You're introducing a memory leak right off the bat by never saving the handle (pointer) to the memory you just dynamically allocated. I would avoid using new unless necessary, and always delete anything you new.