I want to pass an uninitialized object pointer to some method. Within that method I’ll create an instance of the object using the new operator (or malloc) and assign its address to the passed pointer. This is part of my code:
void test(testClass* t){
...
t = new testClass();
...
}
int _tmain(int argc, _TCHAR* argv[])
{
testClass* t = NULL;
test(t);
cout<<t->getTestValue()<<endl;
delete t;
}
My problem is in the _tmain function (after calling test) where I want to call the getTestValue method of the object pointed to by t. Here my program crashes and terminates with an access violation unexpected exception.
It seems an object created dynamically (using operator new and even malloc) is not usable outsie of the scope of the function test. Can anybody help?
To change a pointer in a function, it must be passed by reference:
Otherwise, the change made inside the function is not visible on the outside.
Your original pointer doesn’t get changed, remains
NULL, and thus runs into undefined behavior and a crash.Whenever you pass a parameter by value, a copy is made inside a function. So when you do
t = new testClass();, you’re actually working on a copy of your pointer.