-4

I am learning C++ and have a problem with pointers. I want to pass a pointer into my method and assign it a new value. But my pointer is 0 after the method was called. What am I doing wrong? Thanks

#include <iostream>

using namespace std;

class MyObject
{
    public:
        bool search(int* a) 
        {
            int* test = new int(23);
            a = test;
            return true;
        }
};


MyObject* obj;

void search()
{
    int* test = NULL;
    obj->search(test);
    cout << test << endl;
}

int main(int argc, char *argv[])
{
    obj = new MyObject();
    search();
}
3
  • @StaticBeagle None of the answers there seem to show how to pass a reference to a pointer. I'm not sure it's a good duplicate. Commented Jun 1, 2018 at 5:11
  • Unrelated: Consider making obj an automatic variable inside main and passing it into search as a parameter. Global variables are not strictly bad, but they can make your life harder than it needs to be as your programs grow more complex.. Commented Jun 1, 2018 at 5:23
  • @rwp that code is only C if agajvery is using some really impressive macros. Commented Jun 1, 2018 at 6:14

3 Answers 3

3

You need to pass the pointer by reference.

bool search(int*& a)

Without this, the pointer is passed by value, and you are only assigning a copy of what you passed. To assign the actual object/variable you pass, you need to pass the pointer by reference.

For further reading: What's the difference between passing by reference vs. passing by value?

Sign up to request clarification or add additional context in comments.

3 Comments

Where is the explanation of why, and what's the difference, between pass-by-reference, and pass-by-value?
Added explanation
Perfect. Succinct and hits on all the key terms an asker needs to perform research for more information should they want it.
0

a is a local variable, if you set its value during the search method execution, it won't have any effect on the test variable in the free search function, because a is just a copy of test.

You should pass a by reference:

bool search(int *&a) { 
    int* test = new int(23);
    a = test; 
    return true; 
}

Comments

0

The pointer was passed by value instead of reference. Which means the local variable test's value was not changed.

Instead do bool search(int*& a)

This will pass the reference to the method, which will update the local variable in the calling function.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.