Search code examples
c++boostptr-vector

Accessing derived objects in boost::ptr_vector


I am using a boost::ptr_vector < class A > , which I also use to store objects of class B : public class A. I want to be able to access the class B objects in the vector; how do I cast to get access?


Solution

  • Ideally, A should provide a virtual interface that allows you to access the parts of B that you need. If you need to access the actual B objects, you would need to use dynamic_cast on the reference yielded by an iterator into the container (you could use static_cast if you knew with certainty that the iterator actually pointed at a B object):

    // Create a container and insert a new element into it:
    boost::ptr_vector<A> s;
    s.push_back(new B());
    
    // Get a reference to that element we just inserted:
    B& b_ref = dynamic_cast<B&>(*s.begin());
    

    If you wanted to iterate over all the B elements in the container (and skip over any non-B elements), you could do that fairly easily using a combination of Boost's transform_iterator (to convert each A& to a B&) and filter_iterator (to skip over any non-B elements in the container).