Ilya Zlatkin
Ilya Zlatkin

Reputation: 86

How to disable slicing in C++?

Could slicing be disabled in C++ using any environment variable or any cflags options?

Is any way to disable it by default?

Upvotes: 0

Views: 314

Answers (1)

Jeremy Friesner
Jeremy Friesner

Reputation: 73364

No -- object slicing is an unavoidable consequence of C++'s pass-by-value/copy semantics and can't be avoided except by not trying to copy a subclass object to a superclass-object.

The way to deal with unwanted object-slicing is to avoid copying; use pass-by-reference instead, or if you absolutely must have an unsliced/polymorphic copy of an object (e.g. because you're going to want to modify the copy and don't want to modify the original) you'll need to implement some kind of virtual std::unique_ptr<BaseClass> clone() const method on your objects, so that you can call clone() on the object you want to copy and have clone() dynamically allocate, copy-construct, and return-by-pointer a copy of itself that includes all the correct subclass data.

Upvotes: 3

Related Questions