Do You Know "Object Slicing"?
Object slicing in C++

Do You Know "Object Slicing"?

When you try to copy a subclass object to a superclass object, the superclass object does not have any member variables and member functions in the subclass. Therefore these variables and functions have been “sliced off”.

For example, let’s assume the class hierarchy is something like this.

No alt text provided for this image


Then, if you assign “B” object to “A”, you will lose all the attributes of “B”.

No alt text provided for this image

Slicing is allowed by the compilers, which is highly discouraged because this will make the code more unmaintainable.

Here the object “a” does not have any unique features of “B”. Hence it behaves like an “A” object.

Some experts say, slicing could cause memory corruption.?

要查看或添加评论,请登录

Lahiru Dilshan的更多文章

社区洞察