What is object slicing in C++? How can you avoid it?
Show answer and explanation
Object slicing occurs when a derived object is copied into a base object by value, so the new object contains only the base subobject and loses derived state and behavior. Avoid it by passing and storing polymorphic objects through references or owning smart pointers, and give a polymorphic base a virtual destructor. When true value semantics are required, use a virtual clone, type erasure, or a closed sum type such as std::variant instead of accidental base-value copies.
Object slicing occurs when a derived object is copied into a base object by value, so the new object contains only the base subobject and loses derived state and behavior. Avoid it by passing and storing polymorphic objects through references or owning smart pointers, and give a polymorphic base a virtual destructor. When true value semantics are required, use a virtual clone, type erasure, or a closed sum type such as std::variant instead of accidental base-value copies.
Connect the conclusion directly to the type, lifetime, ownership, overload-resolution rule, or library contract present in the question. State implementation dependence or a violated precondition explicitly instead of merely guessing output.