SpeedyV
SpeedyV

Reputation: 41

Pass reference to a pointer

I have the following problem in C++:

class Class3
{
    //...
};

class Class1
{
public:
void func1(Class3* class3Pointer)
{
    Class3 *myClass3 = new Class3();

    //The newly created object myClass3 should be referenced by class3Pointer
    class3Pointer = myClass3;

    //But I need to work with myClass3 object now in main function below, after myClass3 has been initiated.

    //I want to do that while a loop is sleeping
    while(true) {
        sleep();
    } 
}

};

class Class2
{
    public:
    void func2(Class3* class3Pointer)
    {
        Class1 *Class1Object = new Class1();
    Class1Object->func1(class3Pointer);
}

};




int _tmain(int argc, _TCHAR* argv[])
{
    Class3* class3Pointer;

    Class2 *myClass2 = new Class2();

    myClass2->func2(class3Pointer); //Calling in a new thread

    //Here, I need to work with object myClass3 instantiated in Class1->func1

    return 0;
}

In the main method I want to refer with myPointer to the Object created within Func2. How can I do that? I think, the way above is wrong because it is just passing the myPointer twice by value. How can I pass the pointers by reference?

Thanks for any help. The use case is tcp socket programming.

Best,SpeedyV

Upvotes: 0

Views: 63

Answers (1)

M.M
M.M

Reputation: 141544

Make the function take its argument by reference:

void func1(Class3* & class3Pointer)
// ----------------^

Then changes to class3Pointer in the function will also change the argument that was passed (in fact both of those two things will denote the same variable).

Upvotes: 1

Related Questions