c++ - How can I access dynamically created objects which are created out of the scope of the current function? -
i want pass uninitialized object pointer method. within method i'll create instance of object using new
operator (or malloc
) , assign address passed pointer. part of 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 in _tmain
function (after calling test
) want call gettestvalue
method of object pointed t
. here program crashes , terminates access violation unexpected exception.
it seems object created dynamically (using operator new
, malloc
) not usable outsie of scope of function test
. can help?
to change pointer in function, must passed reference:
void test(testclass*& t)
otherwise, change made inside function not visible on outside.
your original pointer doesn't changed, remains null
, , runs undefined behavior , crash.
whenever pass parameter value, copy made inside function. when t = new testclass();
, you're working on copy of pointer.
Comments
Post a Comment