0

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

Is any way to disable it by default?

Yakov Galka
  • 70,775
  • 16
  • 139
  • 220
  • I think this is relevant to the question: https://www.geeksforgeeks.org/object-slicing-in-c – selbie May 27 '21 at 23:40
  • short answer: move the copy constructor and assignment operator to private or tag with delete. Or just use references and pointers instead of assignment by value. – selbie May 27 '21 at 23:42
  • 1
    What do you mean with disable? Do you want a compiler error if there is objects slicing somewhere in your code?? –  May 28 '21 at 00:08

1 Answers1

3

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.

Jeremy Friesner
  • 70,199
  • 15
  • 131
  • 234
  • 2
    It can also be avoided by overloading constructors to give a compilation error for an attempted slice – M.M May 28 '21 at 00:09