This answer suggests that object slicing in vectors can be overcome with the use of pointers. From my testing, this is true when working with variables shared between the base and derived classes. For example, given these classes:
class Base {
public:
int x = 1;
};
class Derived : public Base {
public:
Derived() : Base() {
x = 2;
}
int y;
};
it can be seen that Derived redefines x to be 2 upon construction. When placed into a vector of the Base class, the x variable behaves as expected.
vector<unique_ptr<Base>> baseVec; // Vector of pointers to Base objects
unique_ptr<Derived> derivedPtr(new Derived()); // Pointer to Derived object
baseVec.push_back(std::move(derivedPtr)); // Add pointer with std::move()
std::cout << baseVec[0]->x << std::endl; // Outputs 2
However, attempting to use the y
variable belonging only to Derived leads to an error, C2039: 'y' is not a member of 'Base'
as seen here:
std::cout << baseVec[0]->y << std::endl;
Is there a way to bypass this issue while preserving member variables unique to derivative classes, and if not is there a superior way to store objects in an ordered container?
Edit
Relevant contents of the previous edit have been moved to my answer below. I do not plan to accept the answer until I can find a way to use smart pointers (or ensure that my raw pointer implementation does not have memory issues).