pass address of an object to another object C++

Viewed 540
int main(){

  Test obj1(a,b,c);

  Test obj2(d,e,f);

  &obj1=&obj2;//This line wont work saying lvalue required on left side

}

What can i do to counter this error? I want to store address of obj2 into obj1 so their member variables become same(a=d,b=e,c=f) and when i change a member variable of obj1, it changes in obj2 aswell.

2 Answers

What you are doing is like 42 = 64. It makes no sense. If you want to store the address of an object, you can use a pointer object:

Test obj1;
Test obj2;

Test * pobj = &obj1; // pointing to obj1
pobj = &obj2; // pointing to obj2

You could also use a reference to accomplish something similar, but since you mentioned you want to be able to rebind to a different object after the declaration, pointers are a better fit for your use case.

so their member variables become same(a=d,b=e,c=f) and when i change a member variable of obj1, it changes in obj2 aswell.

What you want is not pointers or addresses. What you describe is a reference:

Test obj1(a,b,c);

Test& obj2 = obj1;

If you want to be able to rebind the reference then use std::reference_wrapper:

Test obj1(a,b,c);
Test obj1b(d,e,f);

auto obj2 = std::ref(obj1);
obj2 = obj1b;
Related