"simple" swap

Hey guys,

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?

Thanks!
Last edited on
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.


What is confusing you?
ok maybe I didn't make my intentions clear. I want to swap the addresses, not the values of the pointers!
closed account (zb0S216C)
xander333 wrote:
I want to swap the addresses, not the values of the pointers! (sic)

Confusing, much. You cannot swap addresses, only the content within them.

Wazzak
xander333 - Are you saying that you want to swap the address of this with that of the other variable??
Last edited on
Hmm I see. Damn I thought you could swap addresses xD

thanks all!
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?
h9uest wrote:
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.
@ne555:
Thanks for pointing out my mistake.
It simply fails because the type of b is different to the type of a.
With the same type you can actually swap the contents of a and b.
Topic archived. No new replies allowed.