I read other questions trying to figure this out but I didn't find much like what I have in mind. I'm kinda new to C++ and I just don't want to have my C++ code to look like "C with classes", or in other words, if there is a good "C++ way of doing this", that's what I'm looking for, but I'm a bit confused. Well, to the problem.
I have a class, say MyClass
. Now, in other class, say MyContainer
, I have a vector<MyClass> vec
.
Let's say I'm now creating a method that populates a MyClass
object with any arbitrary stuff and then pushes it into vec
. First question is: should I allocate and push the object like the following? (using vector<MyClass> vec
)
MyClass *obj = new MyClass(args);
vec.push_back(*obj);
I am not sure this is right, but by my understanding, this could make me avoid having to manually delete every instance of MyClass
I put into vec
when the instance of MyContainer
is of no use anymore.
What bugs me is that, like I said, this does not seem right anyway, and the other way I can figure out is declaring vector<MyClass*>
and writing:
MyClass *obj = new MyClass(args);
vec.push_back(obj);
But this would make me write a method to delete every instance of MyClass
I created before, right?
So... What should I use and, if both are actually right, when one is preferrable to the other?
However, if everything is wrong from the start, how can I do this?
Thank yall!
PS: by the way, MyContainer
is created in main(). I'm planning to use heap allocation. Should I?
Edit: I can't use C++11.
PS2: This is part of an assignment, but I found it general enough to be of use for anyone, not just me.