tags:

views:

102

answers:

4

I have a function A(), that returns a pointer to an object. In function B() I try to change a member of that object in the following way:

void B()
{
    ObjType o = *getObj();
    o.set("abc");
}

Object o is stored in an array, and when I print the value of the member, it seems nothing happened, and the member still has the old value;

The solution is quite simple:

void B()
{
    ObjType * o = getObj();
    o->set("abc");
}

This does work. But to me, this is quite the same as the first sample. Can anyone explain this?

+4  A: 

The first one creates a copy of the object. The second one creates a pointer to it. In the first case, you are modifying the copy.

Brian
+9  A: 

The following line is most likely copying the object:

ObjType o = *getObj();

That's why nothing happens. If you don't want to use a pointer as shown in your second snippet, you can use a reference like this:

ObjType& o = *getObj();
o.set("abc");
gix
Ok, but can you explain why it makes a copy?
Ikke
When you write "Objttype o" you ask the compiler to create a new object, not a reference or pointer. It allocates storage and invokes a copy constructor.
sharptooth
+3  A: 

Of course it's not the same. The first one copies the object pointed to by the returned pointer into a local object on your stack, then modifies the copy.

The second one retains a pointer to the object returned, and modifies that through the pointer, thus changing the original.

A third solution would be to use references.

unwind
+2  A: 

The two are quite different:

   ObjType o = *getObj();

creates a new copy of the object called o

   ObjType * o = getObj();

creates apointer called o which points to an existing copy - no new object created

anon