I have these classes:
class Element{
};
class Button : public Element{
};
class Label : public Element{
};
class Input : public Element{
};
And I want to be able to create a void add(const Element & e)
function that would insert derived class object into a vector of shared_ptrs. The answers I've found suggested something like this:
vector<shared_ptr<CElement>>> vec;
vec.push_back(make_shared<DerivedClass>());
Which could work if I made an overloaded add function for each derived class, but that seems like a miserable solution.
So my question is: How do I insert a derived class object into a vector<shared_ptr<CElement>>>
without knowing what derived class I'm trying to insert?
That's the beauty of casting. Your derived classes can be downcasted to the base class.
void add(std::shared_ptr<Element> ptr) {
vec.push_back(ptr);
}
add(std::make_shared<Button>()); // std::shared_ptr<Button> casted to std::shared_ptr<Element>
Just don't forget to have a virtual destructor in your base class to avoid resource leaks!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.