How to upcast the vectors in my subclasses to superclass so that I can just use one pointer to modify and browse through the objects in the vectors? Thank you in advance!
class S { ... };
class A : public S { ... };
class B : public S { ... };
class C : public S { ... };
int main(){
vector<A> aVec;
A a;
a.addList(aVec, ...some attributes...); //add objects into aVec using a function in class S
a.addList(aVec, ...some attributes...);
vector<B> bVec;
B b;
b.addList(bVec, ...some attributes...); //add objects into bVec using a function in class S
vector<C> cVec;
C c;
c.addList(cVec, ...some attributes...); //add objects into cVec using a function in class S
}
One way to do this is to have a std::vector<std::unique_ptr<S>> and create your objects like std::unique_ptr<S>(new A) and store them in the vector as appropriate.
Using unique_ptrs not just raw pointers will ensure your objects are appropriately destructed just like they would be if they were directly stored in the vector.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With