Search code examples
c++object-reference

Is there any way to change an outside object from inside a function


Is it possible to define a function which will make the argument refer to another (already existing) object after it returns without using pointers, etc? Again, this can't just change the existing object by using a copy constructor or assignment operator or anything. The outside object would refer to a different block of memory when the function returned.

For example:

int x;
void change(int& blah) {
    blah = x; // I don't want to change blah's value to x's value, I want to make blah refer to x outside the function
}

void main() {
    int something = 0;
    change(something);
    assert(&x == &something);
}

Regardless of the method used, the function must be called like

change(x);

Without applying any special operator or function to the argument before calling the function. I don't know if this is possible, but it would make very cool things possible if it is. If it's not, I would also like to know why.


Solution

  • No, because something and x are different objects. They don't refer to different objects. They don't point to different objects. They are different objects.

    To change where something points, that something needs to be a pointer. If you have a pointer, you can do this:

    int x;
    
    void change(int*& p)
    {
        p = &x;
    }
    
    int main()
    {
        int something = 0;
        int* pointer = &something; // pointer points to 'something'
        change(pointer);           // now pointer points to 'x'
        assert(&x == pointer);
    }