Class scope

Hi all,
I'm new to classes and need a hand if you don't mind. :) I'm creating a set of three classes - one class contains a couple of vectors filled with pointers to all the instances of the other two classes, and that 'parent' is global.

Where do I instantiate a new instance of the child classes? If I have a global function outside of any classes in my script which creates a new instance and appends a pointer to it onto the parent class' vector, then when my function ends, won't the new class instance be destroyed with it just like any local variable, rendering the pointer in the vector useless outside of this function?

If that's the case, how do I get around it? Do I have to add a function to the parent class called AppendItem and create the child instance inside the parent to allow it to remain with its parent's scope?
You allocate memory for it, anywhere, in a non-member non-friend function, in some other class, through a factory, in a separate thread. The key here is you allocate the memory and you then you push it into your parents vector of pointers container. Just don't forget to delete the memory when you are done with it.

1
2
3
4
5
6
7
8
void SomeFunction()
{
    //...
     Obj * pointerToSomeObj = new Obj;
     parent.push_back(pointerToSomeObj);
    //...
}
Last edited on
So the object space allocated by 'new' remains after the function closes, but the variable pointerToSomeObj is local to the function and is destroyed after the function returns, so we copy pointerToSomeObj into the vector, which is global, and that way we can access our new instance from wherever until we finally choose to 'delete' it?
Exactly. new allocates memory on the free store whereas automatic variables are created on the stack.
Topic archived. No new replies allowed.