1

EDIT: I have fixed the accidental argument typo in func2() to be MyClass* not MyClass.

I have a class like this:

#include "MyClass.h"

class X{
    public:
        X();
        MyClass* m;
        func1();
        func2(MyClass* m, int x);

    private:
}

Source:

#include "X.h"

X::X{
    m = null_ptr;
}

X::func1(){
    //Pass the un-initialized data member m here...
    func2(m, 6);

    //When I get to this point m has not been assigned, even though it was passed as a pointer to func2()
}

X::func2(MyClass* old_obj, int x){
    //Please forgive the memory management for a second....
    MyClass* new_obj = new MyClass(x);

    //This should initialise the data member m??????
    old_obj = new_obj ;
}

However it doesn't work- am I making a fundamental miss-assumption here? I thought this would work....

user997112
  • 29,025
  • 43
  • 182
  • 361

1 Answers1

6

To modify a pointer from function parameter, you need to modify original pointer not it's copy.

 func2(MyClass*& m, int x);
 //            ^
billz
  • 44,644
  • 9
  • 83
  • 100
  • I did wonder this...... :) However I thought pointers were primitives so there was no "by copy" passing??? – user997112 Nov 09 '13 at 01:19
  • @user997112: No, if you want to modify the original pointer you need to either know the address of the pointer (the approach used in C APIs) or pass the pointer by reference. – Andon M. Coleman Nov 09 '13 at 02:02