Dave S
Dave S

Reputation: 1009

Pointer value loses scope

In the method callTest I declare a pointer to an int called testPtr. I then pass it to the method test where it is assigned. Since the pointer is no longer nullptr I can print the value. However, when I leave the scope of a::test, I see the pointer is null again. I am perplexed as to the reason why.

class a
{
public:
   a();

protected:
    void a::callTest()
    void test(const int* intPtr) const;

private:
    int mIntTest;
}

a::a() : mIntTest(7)
{

}
void a::callTest()
{
    printf("a::callTest mIntTest = %d\n",mIntTest);
    int* testPtr = nullptr;
    // set the value of the pointer
    test(testPtr);
    if (testPtr == nullptr) {
        printf("a::callTest testPtr STILL NULLPTR\n");
    } else {
        printf("a::callTest test ptr = %d\n",*testPtr);
    }
}

void a::test(const int* intPtr) const
{
    intPtr = &mIntTest;
    if (intPtr != nullptr) {
        printf("a::test intPtr = %d\n",*intPtr);
    }
}

output:
s::callTest mIntTest = 7
a::test intPtr = 7
a::callTest intPtr STILL NULLPTR

Upvotes: 0

Views: 355

Answers (1)

cigien
cigien

Reputation: 60238

You need to pass the pointer by reference:

void a::test(const int* & intPtr) const
                    //  ^  like this

otherwise you are passing it by copy, and changes made inside the function will not be visible to the caller. This is no different than when you pass an int by copy vs by reference, the behavior is the same.

Upvotes: 2

Related Questions