user63898 user63898 - 9 days ago 6
C++ Question

c++ when copying inner function pointer to object to function passed pointer the value don't change

i want to change the pointer to where it point to with out success
here is what i have :

class Test {
public:
Test() {};
~Test(){};
int foo;
};
void ToPointer(Test *tst)
{
Test* t1 = new Test();
t1->foo = 111222;
tst = t1;
}

Test *t2 = new Test();
t2->foo = 2;
ToPointer(t2);
int fff = t2->foo;


The result of fff is still 2

i want t2 to point to t1 or at list copy all its values

here i just simplify it with foo but in real life the object is much more complex

i dont what to use reference to pointer ( * &)

Answer

Since pointers are passed by value, and you don't wish to use reference-to-pointer, you could use pointer-to-pointer like this:

#include <iostream>

using namespace std;

class Test {
public:
    Test() {};
    ~Test(){};
    int foo;
};

// tst will be a pointer to the pointer (address) of the Test instance.
void ToPointer(Test** tst)
{
    Test* t1 = new Test();
    t1->foo = 111222;
    *tst = t1;  // you can use the pointer tst, 
                // even though it is a copy of the original argument,
                // because it points to the pointer that points to the Test instance.
}

int main()
{
    Test* t2 = new Test();  // t2 stores the address of the Test instance
    t2->foo = 2;
    ToPointer(&t2);         // send ToPointer() the address of t2, 
                            // which is itself a pointer to the Test instance
    int fff = t2->foo;
    cout << fff << endl;    // verify that fff is 111222

    return (0);
}