Is there any example of the C++ object slicing effect which can cause undefined behavior, memory leak or crash in an otherwise correct set of code? For example when class A and B (inherited from A) are correct and sound, but calling a void f(A a) demonstrably causes nasty things.
It is needed for forming a test question. The goal is to know if the participant is aware of the slicing phenomenon or not, using an example code snippet whose correctness must not be a matter of opinion.
If
Ais indeed “correct and sound”, then slicing (copying the base sub-object) is well-defined and will not cause any of the problems you mention. The only problem it will cause is unexpected behaviour, if you expect the copy to behave likeB.If
Ais not correctly copyable, then slicing will cause whatever problems arise from copying objects of that type. For example, if it has a destructor which deletes a pointer held by object, and copying creates a new pointer to the same thing, then you will get undefined behaviour when both destructors delete the same pointer. This isn’t a problem with slicing as such, but with invalid copy semantics of the sliced object.