Have you ever tried inserting derived class objects (not pointers to objects) to a vector of base class objects? Then what happens is the derived class objects are sliced to base class objects. See the following example.
class CBase
{
public:
int m_BaseVariable;
};
class CDerived : public CBase
{
public:
int m_DerivedVariable;
};
int main()
{
vector<CBase> BaseVector;
CDerived MyDerived;
BaseVector.push_back(MyDerived);
.............
return 0;
}
Now if you watch BaseVector in a debug window, you can see that it does not have the variable m_DerivedVariable. It has been sliced to the base class object.
Of course, the same slicing will happen if you make an assignment
CBase MyBase = MyDerived;
However, things will be complicated and more error prone in a vector where you can push both base type objects and derived type objects.
Be aware of the above pitfall. At least the compiler (VC++ 6.0, I’m not sure about others) is not giving any error or warning.
September 18, 2008 at 2:55 am
Hi
I like your posts, It sets me thinking.