In C++, what happens when a Reverb object is stored in a std::vector<Effect> or passed to a function taking Effect by value?
answer
- a copy, not the original
- the base copy constructor runs
- dynamic type becomes the base
- pointers, references or abstract bases
basics
~10 sThe Reverb is sliced: Effect's copy constructor builds a brand-new Effect from the Effect part of the Reverb, so Reverb's data is lost and virtual calls on the copy run Effect's functions, not Reverb's.
solid answer
~40 sCopying a derived object into a base-class **object** calls the base's copy constructor, which binds the `Reverb` to a `const Effect&` and copies only the `Effect` members. The result is a new object whose dynamic type is `Effect`, so `chain[0].name()` and a by-value parameter's virtual calls run `Effect`'s versions and Reverb's members are simply gone. This is **object slicing**, and it compiles silently. A related form is assignment through a base reference: `Effect& a = r1; a = r2;` copies only the `Effect` part, leaving `r1` half old and half new. Polymorphism needs **indirection**: store `std::unique_ptr<Effect>`, pass `const Effect&`. Making `Effect` abstract turns every slicing copy into a compile error, and a virtual `clone()` gives polymorphic copies when you need them.
code
cpp · 29 lines#include <cstdio>
#include <memory>
#include <vector>
struct Effect {
float mix = 1.0f;
virtual ~Effect() = default;
virtual const char* name() const { return "bypass"; }
};
struct Reverb : Effect {
float decaySeconds = 2.5f;
const char* name() const override { return "reverb"; }
};
void byValue(Effect e) { std::puts(e.name()); } // copies only the Effect part
void byRef(const Effect& e) { std::puts(e.name()); }
int main() {
Reverb r;
std::vector<Effect> chain;
chain.push_back(r); // sliced on the way in
std::puts(chain[0].name()); // bypass
byValue(r); // bypass
byRef(r); // reverb
std::vector<std::unique_ptr<Effect>> owned;
owned.push_back(std::make_unique<Reverb>());
std::puts(owned[0]->name()); // reverb
}go deeper
Recall that copying a derived object into a base object keeps only the base part, so virtual calls on the copy run the base versions.
Explain the mechanism: the base copy constructor binds the derived object to const Base& and builds a new object whose dynamic type is the base; then name the four fixes.
Spot the quiet forms in review: by-value containers, by-value parameters and handlers, and partial assignment through a base reference, and show how an abstract base turns them into compile errors.
Set a rule for polymorphic hierarchies: bases abstract or with protected copy operations, ownership through unique_ptr, clone() where copies are needed, so slicing cannot compile.
## What slicing is **Object slicing** happens whenever an object of a derived class is used to initialise or assign an object, not a pointer or reference, of a base class. In the audio framework below, `Effect` is a concrete base with a pass-through default, and `Reverb` adds data and overrides `name()`: ```cpp struct Effect { float mix = 1.0f; virtual ~Effect() = default; virtual const char* name() const { return "bypass"; } }; struct Reverb : Effect { float decaySeconds = 2.5f; const char* name() const override { return "reverb"; } }; ``` Each of these creates a new `Effect` object from a `Reverb`: - `Effect copy = reverb;` copy-initialisation of a base object; - `void byValue(Effect e)` called with a `Reverb`; - `std::vector<Effect> chain; chain.push_back(reverb);` the vector stores `Effect` elements by value; - returning an `Effect` by value from a function whose local is a `Reverb`; - catching an exception by value as `catch (Effect e)`, which is why handlers catch by reference. ## Why the copy forgets it was a Reverb C++ resolves the initialisation with `Effect`'s **copy constructor**, `Effect(const Effect&)`. A `Reverb` binds to `const Effect&` because `Effect` is a public base, so the call is legal and needs no cast. That constructor knows only `Effect`'s members, so it copies `mix` and nothing else. The object it builds is a complete `Effect`: its **dynamic type is `Effect`**, and in common implementations its hidden vtable pointer is `Effect`'s. Virtual calls on it therefore run `Effect::name()` and print `bypass`, and `decaySeconds` is gone for good. Nothing about the copy is undefined or broken; it is exactly the object you asked for, which is why compilers stay silent. ## Partial assignment: the quieter variant ```cpp Reverb r1, r2; Effect& a = r1; a = r2; // Effect::operator=, not virtual ``` Assignment operators are ordinary member functions, and the implicit `Effect::operator=` is not virtual. Through `Effect&` it copies `mix` from `r2` into `r1` and leaves `r1.decaySeconds` alone. `r1` is now a mix of two objects' state. Making `operator=` virtual does not really help, because the override would take a `const Effect&` and still cannot know the other operand's dynamic type. ## Four ways to stop it 1. **Hold polymorphic objects through indirection.** Store `std::vector<std::unique_ptr<Effect>>`, pass `Effect&` or `const Effect&`, return `std::unique_ptr<Effect>`. Dynamic dispatch then sees the real object. 2. **Make the base abstract.** If `Effect` has a pure virtual function, no `Effect` object can be created, so every slicing copy above becomes a compile error. Apple clang 21 rejects `Effect copy = r;` with `error: variable type 'Effect' is an abstract class`, and `std::vector<Effect>::push_back` fails inside the library with `allocating an object of abstract class type 'Effect'`. 3. **Restrict copying in the base.** Declaring the base's copy constructor and copy assignment `protected` lets derived classes copy their base part while outsiders cannot slice. Deleting them outright also deletes the implicit copy operations of every derived class. 4. **Offer polymorphic copying explicitly.** A `virtual std::unique_ptr<Effect> clone() const` overridden in each class returns a full copy of the dynamic type. | Approach | Slicing possible? | Cost | |---|---|---| | `std::vector<Effect>` | yes, silently | none, but wrong behaviour | | `std::vector<std::unique_ptr<Effect>>` | no | one allocation per effect, pointer chasing | | abstract `Effect` | compile error | base cannot carry a usable default | | protected copy operations | compile error outside the hierarchy | derived classes write their own copy if needed | ## The copy you did not write Type deduction produces slicing copies that nobody typed as copies. `auto` drops references, so given `Effect& current = *owned[0];`, the line `auto fx = current;` deduces `Effect` and builds a sliced copy, while `auto& fx = current;` keeps the reference. A lambda that captures `current` by copy, as in `[current] { ... }`, likewise stores a sliced `Effect`. In review, any `auto` or by-copy capture initialised from a polymorphic base reference deserves a second look. ## Where slicing is intended Slicing is occasionally what you want: copying the `Effect` settings shared by all effects into a preset object, for example. Even then, make it explicit with a named function such as `EffectSettings settings() const` so a reader sees the conversion. A container of a closed set of concrete types held by value is a different design, using `std::variant`, and does not slice because it never converts to a base.
- How do you copy a polymorphic object without slicing when you only hold an Effect&?Add a virtual `clone()` to the base, for example `virtual std::unique_ptr<Effect> clone() const = 0;`, and implement it in each class as `return std::make_unique<Reverb>(*this);`. The call dispatches on the dynamic type, so the copy is a full `Reverb`. Because smart pointers are not covariant, every override keeps the `std::unique_ptr<Effect>` return type.
- Why do exception handlers catch by reference rather than by value?A handler written as `catch (Effect e)` copy-initialises an `Effect` from the thrown object, which slices a thrown `Reverb`-derived error type and loses its overrides and data. `catch (const Effect& e)` binds to the thrown object itself, so virtual calls such as `what()` on a standard exception reach the most-derived override.
Photocopying a passport onto a form that only has boxes for the name and the photo: the copy is a perfectly valid form, but the visa pages are gone and nothing about the copy remembers they existed.
- Virtual functions keep working on the copy because the vtable comes along.
- std::vector<Effect> can hold Reverb objects as long as Effect has a virtual destructor.
- Slicing is undefined behaviour that the compiler is not required to diagnose.
- Assigning through an Effect& copies the whole Reverb, since the reference refers to a Reverb.
- Marking Reverb final prevents it from being sliced.