Point two objects to the same location

Discussion in 'C++' started by singhal.prateek@gmail.com, Jun 10, 2006.

  1. Guest


    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.

    , Jun 10, 2006
    1. Advertisements

  2. Alan Johnson Guest

    Use a reference.

    TestClass obj1 = new TestClass() ;
    TestClass & obj2 = obj1 ;
    Alan Johnson, Jun 10, 2006
    1. Advertisements

  3. Rolf Magnus Guest

    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

    TestClass& ob2 = ob1;

    That creates a reference to ob1. Now you can use ob2 and ob1 interchangably
    to refer to the same object.
    Rolf Magnus, Jun 10, 2006
  4. LuTHieR Guest

    Try using pointers:

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


    LuTHieR, Jun 10, 2006
  5. Phlip Guest

    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.
    Phlip, Jun 10, 2006
  6. Guest

    Thanks all of you. I was stupid not to have figured this out.
    , Jun 10, 2006
  7. Guest

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

    , Jun 11, 2006
    1. Advertisements

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 (here). After that, you can post your question and our members will help you out.