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*>
}