Is object slicing ever useful?

c++, inheritance, object-slicing

Solution

Sure, it can be useful when wanting to drop the derived portion of class, perhaps to drop dependencies.

For example say we have an object system setup where each base belongs to a derived type, and each derived type has various dependencies, perhaps fulfilled through dependency injection. A clone of a base might want to be created, though a completely new set of dependencies for the actual derived type of that base may want to be assigned.

This can be likened to an game engine where there are many types of colliders. Each collider derives from a base interface-like object in various ways. We want to clone a collider to retrieve it's position and scale (from base), but want to place an entirely different derived implementation on-top of this base. "Object slicing" could be a simple way to achieve this.

In reality a component, or aggregate object organization would make a lot more sense than object slicing specifically, but it's mostly the same idea.

Problem

Object slicing happens when we assign or copy an object of derived class to an object of its base class, losing the derived part of it in the process. It has been explained in more depth here: What is the slicing problem in C++?. (Myself, I don't see it as a problem, rather a natural consequence of language's value semantics, but that's not the point of this question.) What I wonder is: are there ever situations where you'd use it purposedly? A situtation where it is the "right tool for the job"?

Original source

Related problems