Reputation: 3
Take the following code
void save(){
Classname object(aString, aInt);
this->getVector().push_back(&object);
}
I'm trying to save to this class's vector a copy of object, but i know for a fact that this doesn't work because object is going to be deleted once i leave save(), so my question is how do i work around this? i would appreciate some code example because i'm migrating from java and might not understand some of this pointer wizardry.
edit:english edit2:copy paste never works!
Upvotes: 0
Views: 95
Reputation: 99172
First, there's no need for this->
, you can just say
getVector().push_back(...);
Second, since you used this->
, I infer that save
and getVector
are two member functions of the same class; if all getVector
does is give access to a vector that is also a member of the class (without any tricks like lazy instantiation), then you don't need it either, you can deal with the vector directly:
theVector.push_back(...)
Now to your question. You're right, object
will pass out of scope-- if it is on the stack. But you can construct it dynamically, on the heap, and it will live until deleted:
void save(){
Classname *ptr = new Classname(aString, aInt);
theVector.push_back(ptr);
}
Now ptr
will pass out of scope, but the copy of ptr
that was added to the vector will not, and that pointer will still point to the object.
Since you want to use polymorphism, I suppose you want the vector to contain base-class pointers which can actually point to objects of derived classes. No problem:
void save(){
Animal *ptr = new Aardvark(aString, aInt);
theVector.push_back(ptr); // <-- the vector is of type vector<Animal*>
}
Upvotes: 1