I am designing a c++ program aiming to show some object oriented practices. My goal is to have:
- An "abstract" class that can't be initialized that has two subclasses that can.
- Use unique pointer to maintain that there is only one copy of these subclasses at once.
I have therefore created a class with a property that is a vector to unique pointers of the abstract class. The idea being that those unique pointers/the vector might hold a mix of the two subclasses.
I have written the following code and I am not sure why it doesn't compile. Somewhere it complains about v tables suddenly when adding the lines in main and I am not sure why that fixes it.
#include <iostream>
#include <vector>
#include <memory>
class Abstract {
protected:
int capacity;
public:
int getCapacity() {
return capacity;
}
public:
virtual~Abstract() = 0;
virtual bool stub();
};
class Specific : public Abstract {
public:
Specific() {
capacity = 9;
}
bool stub() {
return false;
}
};
class Test {
public:
std::vector<std::unique_ptr<Abstract>> vec;
void addIt(std::unique_ptr<Abstract> thing) {
vec.push_back(std::move(thing));
}
};
int main() {
Test t;
std::unique_ptr<Specific> testPtr(new Specific());
t.addIt(std::move(testPtr));
}
Perhaps I am going about abstract classes wrong? Perhaps a vector of unique pointers to abstract class objects is a bad idea. Really not sure.