
std::vector holding different class types sharing a same base class
Hi,
I'm about to add something to a library of mine, and although tests will
compile OK, I'd like to make sure it won't{*filter*}me up in the long run.
Let's say I have two classes derived from a virtual base class as such:
class C_TheBaseClass {
protected:
C_TheBaseClass (void); // Make the class uninstanciable
public:
int m_SomeMember;
enum {
Type_One,
Type_Two
} m_Type;
};
class C_DerivedClassOne : public C_TheBaseClass {
public:
C_DerivedClassOne (unsigned char Value) {
m_Type = Type_One;
m_SmallMember = Value;
};
unsigned char m_SmallMember;
};
class C_DerivedClassTwo : public C_TheBaseClass {
public:
C_DerivedClassTwo (unsigned long Value) {
m_Type = Type_Two;
m_LargeMember = Value;
};
unsigned long m_LargeMember;
};
I'd like a vector to contain instances of DerivedClassOne's or
DerivedClassTwo's. Since they share the same base class and therefore
share the m_Type member, by making my vector a vector of
C_TheBaseClass'es I could, as I iterate through the vector, switch on
m_Type and then use m_SmallMember or m_LargeMember, depending on the
type of class contained in the vector. Here's an example:
C_DerivedClassOne Moo1 (10);
C_DerivedClassTwo Moo2 (2000000);
C_DerivedClassOne Moo3 (30);
std::vector <C_TheBaseClass> m_Vector; // Note that it will contain
instances, not pointers
m_Vector.push_back ((C_TheBaseClass)Moo1); // Added a C_DerivedClassOne
m_Vector.push_back ((C_TheBaseClass)Moo2); // Added a C_DerivedClassTwo
m_Vector.push_back ((C_TheBaseClass)Moo3); // Added a C_DerivedClassOne
for (std::vector <C_TheBaseClass>::iterator ThisVector = m_Vector.begin
(); ThisVector < m_Vector.end (); ThisVector ++)
switch (ThisVector->m_Type) {
case C_Vector::Type_One:
C_DerivedClassOne *One = (C_DerivedClassOne *)ThisVector;
One->m_SmallMember ++;
break;
case C_Vector::Type_Two:
C_DerivedClassTwo *Two = (C_DerivedClassTwo *)ThisVector;
Two->m_LargeMember ++;
break;
};
That sounds good to me (although I'm not 100% sure of the syntax as I
don't have a C++ compiler with me right now), and my test at home
compiles OK... But how would the std::vector know how much space to
allocate for each element it will contain? My C_DerivedClassOne and
C_DerivedClassTwo are of different sizes..!
I realize most people won't have read up to this point, but if someone
does, I'ld really appreciate some enlightenment!
Thanks
Alex