Point two objects to the same location

S

singhal.prateek

Hi,

How can we make two objects point to the same location? For e.g. I have
an object obj1 of a class and I want to have another object obj2 to
point to the member variables of obj1. Something like:

TestClass ob1 = new TestClass();
...
...
...
TestClass ob2 = ob1; // This doesn't work; It just creates a copy of
ob1 in ob2 and both are independent.

ob2.changeMember(); // I want this change to be reflected in ob1

Any help will be appreciated.

Thanks,
Prateek
 
A

Alan Johnson

Hi,

How can we make two objects point to the same location? For e.g. I have
an object obj1 of a class and I want to have another object obj2 to
point to the member variables of obj1. Something like:

TestClass ob1 = new TestClass();
..
..
..
TestClass ob2 = ob1; // This doesn't work; It just creates a copy of
ob1 in ob2 and both are independent.

ob2.changeMember(); // I want this change to be reflected in ob1

Any help will be appreciated.

Use a reference.

TestClass obj1 = new TestClass() ;
TestClass & obj2 = obj1 ;
 
R

Rolf Magnus

Hi,

How can we make two objects point to the same location?

If you want to point, you might want to try a pointer. ;-)
An object _is_ a location (that contains data), so you can't have two
objects at the same location. C++ mandates that every object has a distinct
address.
For e.g. I have an object obj1 of a class and I want to have another
object obj2 to point to the member variables of obj1. Something like:

TestClass ob1 = new TestClass();
..
..
..
TestClass ob2 = ob1; // This doesn't work; It just creates a copy of
ob1 in ob2 and both are independent.

Try:

TestClass& ob2 = ob1;

That creates a reference to ob1. Now you can use ob2 and ob1 interchangably
to refer to the same object.
 
L

LuTHieR

Try using pointers:

TestClass *ob1 = new TestClass ();
TestClass *ob2 = ob1;

Regards,

LuTHieR
 
P

Phlip

Use a reference.

TestClass obj1 = new TestClass() ;
TestClass & obj2 = obj1 ;

Use a reference:

TestClass obj1;
TestClass & obj2 = obj1 ;

Don't use 'new' unless you absolutely need to, and don't use pointers unless
you need their features that references don't have. Until you learn what
these are, use references.
 
S

sandravandale

Thanks all of you. I was stupid not to have figured this out.

No, not stupid. We all start at the same place. The only stupid
question is the one never asked.

-Sandra
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,755
Messages
2,569,535
Members
45,007
Latest member
obedient dusk

Latest Threads

Top