I have a class with a vector as below:
#include <vector>
class Base{};
class Derived: public Base{};
class Foo{
private:
std::vector<Base*> vec;
public:
Foo() = default;
void addObject(const Base* b){
// vec.push_back(new Base(*b));
// vec.push_back(new Derived(*b));
}
};
int main(){
Derived* d = new Derived();
Base* b = new Base();
Foo f;
f.addObject(d);
f.addObject(b);
delete d;
delete b;
return 0;
}
The function addBase may receive Derived's pointers. The line vec.push_back(new Base(b)); is expected to use b's copy to initialize a new object whose pointer will be pushed_back. If I don't use new, I will have resources shared between b and the vector(This is a sin).
I want to maintain polymorphism. How do I ensure objects that are pushed back maintain the type they were assigned during their creation without forcing everything into a Base object.