The syntax is valid, but it doesn't do what you want because testPointer1()
is operating on a copy of the pointer, not the actual pointer itself. So when you assign the address to the newly allocated object, it gets assigned to the copy, not to the original a1
pointer.
Because of this, the address is lost and you get a memory leak. Also, since the original a1
pointer was never modified in the first place, you attempted to dereference a null pointer, which is a bad thing.
I'd say testPointer2()
is the better way to do it, but if you want testPointer1()
to work, try this:
void testPointer1(A*& a)
{
a = new A();
a->num = 10;
}
The parameter type indicates "a reference to a pointer to A
." That way, instead of a copy of the pointer being passed, a reference to the original pointer will be passed. A C++ reference is an alias to another object. So whatever you do on the alias, it gets performed on the original object.
Extra notes:
Note that the parentheses in new A();
are actually significant and their presence or absence makes a difference.
Also note that you must manually delete
all new
'ed objects after you're done with them, or you will get a leak. Typically you would wrap the pointer in its own class and implement RAII or use a smart pointer such as Boost's smart pointers or auto_ptr
, for proper memory management and exception safety.
If you're going to set the value of num
on initialization, why not create a constructor?
class A
{
public:
A(int n) : num(n) {}
int GetNum() const { return num; }
private:
int num;
};
void testPointer1(A*& a)
{
a = new A(10);
}
A* testPointer2()
{
return new A(10);
}
// auto_ptr example, see link in second note above
std::auto_ptr<A> testPointer3()
{
return auto_ptr<A>(new A(10));
}