You have one option: you know that you have a IndexElement
and not a Element
in the vector, and then you can use static_cast<IndexElement*>(elements[i]);
. Be aware that if you don't have only IndexElement
, then this will utterly break.
If you can modify b, then you have another option, by making b virtual. If you don't know, you may have Element
s and IndexElement
s, and in that case use dynamic_cast<IndexElement*>(elements[i]);
and test it the result is nullptr
or not. In this instance, b must be virtual (hence virtual destructor).
(I assume we are in Container
, so direct access its members)
Full trial (that will break because no allocated elements
) with the modified Elements:
#include <vector>
using namespace std;
class Element{
public:
virtual ~Element() {}
};
class Container{
public:
vector<Elements*>elements;
};
class IndexElement: public Element{
int index;
};
int main()
{
Container aa;
static_cast<IndexElement*>(aa.elements[0]);
dynamic_cast<IndexElement*>(aa.elements[0]);
return 0;
}