I created an abstract class and then created child classes that inherit this abstract class.
class A{
public:
virtual A* clone() const = 0;
virtual A* create() const = 0;
~virtual A(){};
// etc.
};
child classes
class B: public A{};
class C: public A{};
I then use an implicit conversion of a child class pointer to a base class pointer in the main function.
int main(){
B* pB = new B();
C* pC = new C();
A* pA = pB; //converting a pointer to A, to a pointer to B
A* pAA = pC; //converting a pointer to A, to a pointer to C
I can now populate a vector with these classes using a pointer of type A and access the child classes via polymorphism.
vector<A*> Pntr;
However I want each child class to take responsibility of its own memory release. I know that I can use unique pointers for this. The question is how do I implement this.
If I code it like this:
pA = unique_ptr<A>(pB);
pAA = unique_ptr<A>(pC);
Then I populate the vector like this:
vector<unique_ptr<A>>Pointers;
Pointers.push_back(move(pA));
Pointers.push_back(move(pAA));
Not sure this will even work. And I am also confused about will actually be destroyed when the vector goes out of scope. Will the converted pointers pA and pAA simply be set to NULL or will the class objects be destroyed - which is my original intention. Some clarity needed.