Slicing of Objects in a C++ Vector

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.

Advertisements

One Response to Slicing of Objects in a C++ Vector

  1. chinaman says:

    Hi
    I like your posts, It sets me thinking.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: