- May 21, 2013
- 3,656
- 60
- 91
I have a Money class, with overloaded multiplication and negative sign operator overloads.
In a different class, I was attempting to store the negative of a product, but I was getting an error about passing 'this' argument. Relevant code and errors follow.
I just want to make sure I understand the issue. It's because my return types are const, so the anonymous const Money object that I return cannot be manipulated by the negative sign.
If I defined a move constructor, and simply returned by value, it would work as I expected it to.
Please let me know how right or wrong that assessment is, and if it's wrong, but the real issue is. I can also upload more code if need be. I don't think I'm completely right, because if it was a const issue, the compiler usually does a better job of telling me so. I'm using g++ 7.3.
Money negative sign overload:
Relevant Money multiplication overload (These are friend functions):
The usage that threw an error:
The error:
In a different class, I was attempting to store the negative of a product, but I was getting an error about passing 'this' argument. Relevant code and errors follow.
I just want to make sure I understand the issue. It's because my return types are const, so the anonymous const Money object that I return cannot be manipulated by the negative sign.
If I defined a move constructor, and simply returned by value, it would work as I expected it to.
Please let me know how right or wrong that assessment is, and if it's wrong, but the real issue is. I can also upload more code if need be. I don't think I'm completely right, because if it was a const issue, the compiler usually does a better job of telling me so. I'm using g++ 7.3.
Money negative sign overload:
Code:
const Money Money::operator -()
{
dollars = -dollars;
cents = -cents;
return Money(dollars, cents);
}
Relevant Money multiplication overload (These are friend functions):
Code:
const Money operator *(const Money &left, const int right)
{
int leftPennies = left.makePennies();
int product = leftPennies * right;
return Money(product / 100, product % 100);
}
const Money operator *(const int left, const Money &right)
{
return (right * left);
}
The usage that threw an error:
Code:
// cash is a private data member of my other class
// This is in one of my constructor bodies
cash = -(hotdogSupply * wholesaleHotdogCost);
The error:
Code:
HotdogStand.cpp: In constructor ‘MyAwesomeBusiness::HotdogStand::HotdogStand()’:
HotdogStand.cpp:18:46: error: passing ‘const MyAwesomeBusiness::Money’ as ‘this’ argument discards qualifiers [-fpermissive]
cash = -(hotdogSupply * wholesaleHotdogCost);
^
In file included from HotdogStand.hpp:4:0,
from HotdogStand.cpp:1:
Money.hpp:22:15: note: in call to ‘const MyAwesomeBusiness::Money MyAwesomeBusiness::Money::operator-()’
const Money operator -();