It's been quite a while since I last made a topic :)
Well here I am again with a question (about a bigint class).
I declared my operator+= as follows:
1 2 3 4 5 6 7 8 9 10 11 12
bigint& bigint::operator+=(const bigint& other)
{
vector<int> result;
int carry = 0;
int sum;
bigint* a = this;
const bigint* b = &other;
if(digits.size() < other.digits.size()) //make sure a is the largest number
{
swap(a, b);
}
What I'm trying to do, is swap the addresses (values remain untouched) of the pointers. But when I use the swap function it says it can't because one of the values is constant. I don't understand: the values aren't even being touched?
The reason you fail seems trivial to me: const bigint* b = &other;
Without looking at
What I'm trying to do, is swap the addresses (values remain untouched) of the pointers.
, I'll tell you what I see from the code you write:
bigint* a = this;
You declare and define a pointer a, which points to some bigint type object.
const bigint* b = &other;
You declare and define a const pointer b, which points to another bigint type object "other".
1 2 3 4
if(digits.size() < other.digits.size()) //make sure a is the largest number
{
swap(a, b);
}
Then you swap a's value and b's value when the condition is met. How do you swap? Inevitably, you need to change the value of pointer b, which is a const pointer.
And here we go, you've just got an error.
Well doesn't standard c give you the ability to manage your own addresses? I was always told that c has some very low level capabilities. Couldn't you just copy the values, copy the addresses, stored in ints, delete the pointers, then create new pointers with the addresses in reverse?
or no?
Inevitably, you need to change the value of pointer b, which is a const pointer.
And here we go, you've just got an error.
Nope, you read it backwards. const bigint* b 'b' is a pointer to a constant object. But the value of 'b' can change.
It fails because you want to assigning to 'a' the address of a constant object.
You can overload swap so it will just a change of pointers.
However that will not work here because 'other' must remain untouched.