I am trying to store a number of objects which are derived from a base class in a std::array(or any other container) without object slicing.
The desired output from the code snippet below is:
Hi from child1!
Hi from child2!
And the code:
#include <iostream>
#include <array>
#include <memory>
class Base {
public:
void hello() {
std::cout << "This shouldn't print\n";
}
};
class Child1 : public Base {
public:
void hello() {
std::cout << "Hi from child 1!\n";
}
};
class Child2 : public Base {
public:
void hello() {
std::cout << "Hi from child 2!\n";
}
};
std::array<std::unique_ptr<Base>, 2> array = {std::make_unique<Child1>(Child1()), std::make_unique<Child2>(Child2()) };
int main() {
for (auto &i : array) {
i->hello();
}
}
The output I actually get from the code is:
This shouldn't print
This shouldn't print
Obviously the derived objects have been sliced. Is there any way to avoid this?
Thanks in advance for any advice you can offer.
virtual.std::make_unique<Base>(Child1())which, of course, did not compile since Base is a virtual class.Basehas virtual methods or not. It just doesn't do what you think it does. It does not return aunique_ptr<Base>pointing to aChild1object. It returns aunique_ptr<Base>pointing to aBaseobject that was passed a temporaryChild1object to its constructor.