Question

i can get where the problem is in this snippet:

I want to reset a pointer inside a function, I achieved to make it works by just returning the pointer, but I could not make it with side effect(passing by pointer).

void function(Object * obj)[{
    obj = new Object();
    cout << obj << endl;
    //return obj;
}

main(){
    Object * obj = 0;
    function(obj);
    cout << obj << endl;
}

In this case the result is:

0x12345678
0

while it was supposed to be

0x12345678
0x12345678

I tried using either pointer of pointer or pointer of references but still could not get through the function. While just returning the value worked like a charm. But i need to do this on several params, and the code s much more complex than it appears here.

Was it helpful?

Solution

If you change your function declaration like so it should work:

void function(Object  * &obj)

In your original code, you were passing the pointer by value which means the function made a copy of the pointer and any changes to the pointer in the function would not be reflected. When you pass by reference you are actually working on the original data, this could potentially be done behind the scenes using pointers.

OTHER TIPS

You may want to see this topic.

Return object by pointer to pointer (C way):

void function(Object ** obj) {
  *obj = new Object();
}


main(){
  Object * obj = 0;
  function(&obj);
...

Return object by reference to pointer (C++ way):

void function(Object *& obj) {
  obj = new Object();
}

main(){
  Object * obj = 0;
  function(obj);
...

when you call

void function(Object * obj){

you are copying the pointer obj, in other words, "function"'s stack now holds a local copy of a pointer named obj. When the function returns this local copy is destroyed. Yo can achieve what you want by:

void function(Object* obj&){

Which will actually pass the caller's obj pointer, by reference. Now any change to obj will be reflected in the caller's scope as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top