I am trying to create a link list, but I am having trouble creating objects inside a function and assigning pointers to their addresses, since I believe they go out of scope when the function exits. Is this true? And, if so, how can I create an object outside the main and still use it?
You are correct, local variables will go out of scope at the end of the function block. You need to create pointers to the objects and allocate them with new. And don't forget to delete the object when you remove it from your list.
If you don't want to deal with the hassles and bugs that come with pointers, see boost::shared_ptr instead.
use the new operator:
void f()
{
CMyObject *p = new CMyObject();
List.AddTail(p); // Or whatever call adds the opbject to the list
}
Pay attention to object deletion when your list is destroyed.
Create the objects with the new operator. ie
void foo( myObject* bar1, myObject* bar2 )
{
bar1 = new myObject();
bar2 = new myObject();
// do something
}
int main( int argc, char* argv[] )
{
myObject* thing1;
myObject* thing2;
foo( thing1, thing2 );
// Don't forget to release the memory!
delete thing1;
delete thing2;
return 0;
}
Why don't you store objects (not pointers to objects) in list? Creator-function will return object.
If you really need list of pointers consider using special pointer list containers (boost::ptr_list
) or storing smart pointers in it (boost::shared_ptr
). To prevent objects going out of scope after returning from function, you need to dynamically allocate them with operator new.