views:

98

answers:

4

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?

+2  A: 

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.

Mark Ransom
+1 boost advocacy... :)
mwigdahl
He seems to be new to the language. My guess is that he is implementing a linked list for a school assignment (Otherwise he would use STL or some such). He probably shouldn't be using third party libraries as that would defeat the point of the assignment. Of course, this is all just conjecture...
2-bits
@2-bits. Its true.
chustar
+2  A: 

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.

Serge - appTranslator
A: 

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;
}
cpatrick
It created new bar1 and bar2 pointers, but can you access those pointers from the main() ?
chustar
bar1 and bar2 are parameters to the function; thus, the memory allocated with the two new operations are pointed two by the pointers passed two the function. After foo is called, thing1 and thing2 point to the exact same memory because the ARE bar1 and bar2. Hope that helps.
cpatrick
A: 

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.

begray