C++ : get inherited type from abstract pointer vector -
so have vector holds pointers of component abstract class , , let's have 2 inherited classes component , foo , bar , there way pointer type "foo" vector?
vector<component*> components; class foo : component; class bar : component; components.push_back(new foo()); components.push_back(new bar());
thanks.
yep:
component* c = components[0]; if (foo* f = dynamic_cast<foo*>(c)) { // utilize f } else { // c not foo. maybe it's bar, or else }
so if want write function find foo*
, (assuming c++11):
foo* find_foo(const std::vector<component*>& components) { (auto c : components) { if (foo* f = dynamic_cast<foo*>(c)) { homecoming f; } } homecoming nullptr; }
the cast, dynamic_cast<foo*>
either homecoming valid foo*
or nullptr
, will not throw. standard §5.2.7.9:
the value of failed cast pointer type null pointer value of required result type.
c++ pointers inheritance vector
No comments:
Post a Comment