Tom Martin
Tom Martin

Reputation: 300

Getting an object of a specific derived class, from a vector of base class objects

Currently I have class A, with derived types, B and C.

class A {};
class B : public A {};
class C : public A {};

I then have a vector of type A, which I append a single object of types B and C. Like so:

std::vector<A*> list = new std::vector<A*>;
list->push_back(new B);
list->push_back(new C);

My main question is: How would I go about getting an object of a specific type (that inherits from A), from this vector?

I have attempted to use templates, though this gives unresolved external symbol error

template <class T>
T* GetObject()
{
    for (A* object : list)
    {
        if (typeid(*object) == typeid(T)) return object;
    }
    throw std::exception("vector does not have object of that type");
}

Upvotes: 0

Views: 63

Answers (1)

Remy Lebeau
Remy Lebeau

Reputation: 596246

Give A a virtual method, such as the destructor (which you should do anyway when writing polymorphic types), and then you can use dynamic_cast:

class A {
public:
    virtual ~A() {}
};

class B : public A {};
class C : public A {};

...

std::vector<std::unique_ptr<A>> list;
list.push_back(std::unique_ptr<A>(new B));
list.push_back(std::unique_ptr<A>(new C));

...

template <class T>
T& GetObject()
{
    for (auto &object : list)
    {
        T *p = dynamic_cast<T*>(object.get());
        if (p)
            return *p;
    }
    throw std::exception("vector does not have object of that type");
}

Upvotes: 2

Related Questions