You can't, here is the problem assuming this code
[code}
class BaseClass
{
...
};
class DerivedClass
{
public:
int m_OnlyInDerivedClass
};
vector<BaseClass> vec;
DerivedClass dc;
vec.push_back(dc);
int zzz = vec[0].m_OnlyInDerivedClass; // this line fails
[/code]
A vector contins an alloctor function that allocates objects of the type the vector stores to enable it to increase it's size as required. The data is copied into these allocated memory blocks using =.
Note that in the vector the type is BaseClass so the vetor stores classes of base type so when dc is stored in the vector all the information only in the DerivedClass is lost as it is cast back to a BaseClass because the vector does not provide the storage to store the extra data, it allocates a BaseClass. The final assignment line does not work and you can not down cast an element of the vector to DerivedClass because the class no longer contains that data.
The solution
don't create a vector of classes, create a vector of pointer to class
-
vector<BaseClass *> vec;
-
-
DerivedClass *dc = new DerivedClass;
-
-
vec.push_back(dc);
-
-
int zzz = dynamic_cast<DerivedClass *>(vec[0])->m_OnlyInDerivedClass;
-
Now because we only store the vector the object being pointed at does not suffer the same loss of data problems because the vector is only storing a pointer to BaseClass and this pointer can be downcast to the correct DerivedClass. However also note that we have to provide the allocation (and deallocation) of the data to store the members of the vector ourselves.