I have a base class which has two child classes derived from it.
class A {};
class B : public A {};
class C : public A {};
I have another class that has a pointer to collection of class A members using a vector, something like this:
vector<A*> *m_collection;
And what I do is to create objects of class B or C and add them to the collection using push_back:
B *myb = new B();
m_collection->push_back(myb);
Then I loop through the collection and try to check using ‘typeid’, but it always returns the base class (A). Is it not possible to know the exact type?
Thank you!
Firstly, there is unlikely to be a reason to create your vector dynamically using new. Simply say:
Then you need to give your base class a virtual function or two. A virtual destructor would be a good start:
without it you cannot safely write code like:
Doing this will also enable run-time type information. Howver, switching on
typeidis not how C++ likes you to use RTTI – you should usedynamic_cast:In general however, it is better to use the virtual function mechanism for dispatch, rather than RTTI.