Hi!
So in the following code i have a class, 'Box', that saves a integer 'value'.
Then i run a function in which i set the global pointer 'my_box' on a new box(5). In that function i can still get the value of the object of the pointer, but if im outside of the function the objects gets deleted and the pointer just points to something else. so for me the output here is:
1 2
(*my_box).value = 5
(*my_box).value = -858993460
fun fact: if i comment 'DoSomethingElse();' i get 5 for both, so the object isnt deleted yet.
How can i keep my object as long as i have a pointer pointing it?
You are trying to assign the address of a local variable box1 to my_box. When a function ends (RegisterBoxes()), it always tends to destroy all of its local variables, that's why when you try to output my_box again you only see garbage (because it points to a piece of data that has already been destroyed)
To solve this, use dynamic allocation (also remember to free it when nolonger necessary) :
Well, every simple or non-complex struct should have that (if they have a constructor other than the default constructor). Just initialize all neccessary members of a struct with default values.
So i always have to create an empty constructor Box::Box() {} as well?
Not necessarily. If you do not supply any constructors, the compiler will provide a default constructor for you. However, you provided a constructor at line 4 that requires an int, so the compiler will not automatically provide a default constructor.
Since it's a good idea to initialize value, you can avoid having two constructors by providing a default value in your constructor.
1 2 3 4 5
// At line 4:
Box (int val = 0); // value will be initialized to 0 if not provided
...
Box a (5); // Initializes value to 5
Box b; // Initializes value to 0