I have the conceptual (not real) class hierarchy as :
struct Pet{};
struct Cat : Pet{};
struct Dog : Pet{};
and the object is as :
Pet p("unknown");
Cat c("Kitty");
Dog D("Tommy");
Now how can I store object p,c,d
in a single container like std::vector
. But I can't figure out a way. When i have std::vector<Pet>
other class sliced down. I can't even store them as pointer on container because pointer still have different type.
Usually the only reason you'd put them in the same container is to use them as the base type, making use of polymorphism to simply not care what the specific type is. This requires using virtual methods. For example:
struct Pet {
virtual ~Pet();
virtual void speak(std::ostream &) const = 0;
};
Pet::~Pet() {}
struct Cat : public Pet {
virtual void speak(std::ostream &) const override;
};
void Cat::speak(std::ostream & o) const {
o << "Meow!\n";
}
struct Dog : public Pet {
virtual void speak(std::ostream &) const override;
};
void Dog::speak(std::ostream & o) const {
o << "Woof!\n";
}
Now we have a virtual method (speak(std::ostream&)
) which we can invoke via a pointer-to-Pet
without knowing the actual type of pet:
std::vector<std::unique_ptr<Pet>> pets;
pets.emplace_back(std::make_unique<Cat>());
pets.emplace_back(std::make_unique<Dog>());
for (auto const & pet : pets) {
pet->speak(std::cout);
}
Displays:
Meow!
Woof!
If you can't treat all of the objects in the container as a base instance like this, there is little reason to have them in the same container to begin with -- what would be the point?