0

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

Is any way to disable it by default?

3
  • I think this is relevant to the question: geeksforgeeks.org/object-slicing-in-c Commented May 27, 2021 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. Commented May 27, 2021 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?? Commented May 28, 2021 at 0:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

It can also be avoided by overloading constructors to give a compilation error for an attempted slice

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.