Creating objects in c++
c++, instance, instantiation, object, pointers
Solution
Simple. The first version creates a local variable on the stack, which gets destroyed automatically when it goes out of scope (at the end of the function)
Your vector just contains a pointer to where the object used to be.
The second version creates an object on the heap, which will live until you eventually delete it.
Problem
I just waste hours on a simple line causing data loss. I have AnotherClass holding a vector of instances of MyClass. This AnotherClass instantiates objects of MyClass the following way: ``` AnotherClass::AnotherClass(){ MyClass myObject(...); myVector.push_back(&myObject); } ``` The address of myObject is afterwards pushed into a vector (with other instances of MyClass), like written in the code. When I start using instances of AnotherClass I notice the values of MyClass were lost (completely random). When I change the code to: ``` AnotherClass::AnotherClass(){ MyClass* myObject = new MyClass(...); myVector.push_back(myObject); } ``` I don't have data loss. Can somebody be so kind to explain me why the second way of creating objects doesn't lead to a loss of data? (without referencing me to books of 1.000 pages)