What Does Slicing Mean in C++

What does slicing mean in C++?

Quoting this lecture:

Slicing


Suppose that class D is derived from
class C. We can think of D as class C
with some extra data and methods. In
terms of data, D has all the data that
C has, and possible more. In terms of
methods, D cannot hide any methods of
C, and may have additional methods. In
terms of existing methods of C, the
only thing that D can do is to
override them with its own versions.

If x is an object of class D, then we
can slice x with respect to C, by
throwing away all of the extensions
that made x a D, and keeping only the
C part. The result of the slicing is
always an object of class C.

slicing http://webdocs.cs.ualberta.ca/~hoover/Courses/201/201-New-Notes/lectures/slides/slice/slide1.gif

Design Principle: Slicing an object
with respect to a parent class C
should still produce a well-formed
object of class C.

Usage Warning: Even though D is-a C,
you must be careful. If you have a
argument type that is a C and you
supply a D it will be sliced if you
are doing call by value, pointer, or
reference. See the example below.

Note on virtual functions. Their
signatures are used to identify which
one to execute.

Watch out for the sliced = operator,
it can make the lhs inconsistent.
Also, the operator= is never virtual,
it wouldn't make sense. For example,
suppose classes A, B are both
subclasses of class C. Just because an
A is a C, and a B is a C, it doesn't
mean you can assign a B object to an A
object. Without run-time type
information you cannot make a safe
assignment.

Object Slicing, Is it advantage?

In C++, you should think of an object slice as a conversion from the derived type to the base type[*]. A brand new object is created, which is "inspired by a true story".

Sometimes this is something that you would want to do, but the result is not in any sense the same object as the original. When object slicing goes wrong is when people aren't paying attention, and think it is the same object or a copy of it.

It's normally not beneficial. In fact it's normally done accidentally when someone passes by value when they meant to pass by reference.

It's quite hard to come up with an example of when slicing is definitively the right thing to do, because it's quite hard (especially in C++) to come up with an example where a non-abstract base class is definitively the right thing to do. This is an important design point, and not one to pass over lightly - if you find yourself slicing an object, either deliberately or accidentally, quite likely your object hierarchy is wrong to start with. Either the base class shouldn't be used as a base class, or else it should have at least one pure virtual function and hence not be sliceable or passable by value.

So, any example I gave where an object is converted to an object of its base class, would rightly provoke the objection, "hang on a minute, what are you doing inheriting from a concrete class in the first place?". If slicing is accidental then it's probably a bug, and if it's deliberate then it's probably "code smell".

But the answer might be "yes, OK, this shouldn't really be how things are structured, but given that they are structured that way, I need to convert from the derived class to the base class, and that by definition is a slice". In that spirit, here's an example:

struct Soldier {
string name;
string rank;
string serialNumber;
};

struct ActiveSoldier : Soldier {
string currentUnit;
ActiveSoldier *commandingOfficer; // the design errors multiply!
int yearsService;
};

template <typename InputIterator>
void takePrisoners(InputIterator first, InputIterator last) {
while (first != last) {
Soldier s(*first);
// do some stuff with name, rank and serialNumber
++first;
}
}

Now, the requirement of the takePrisoners function template is that its parameter be an iterator for a type convertible to Soldier. It doesn't have to be a derived class, and we don't directly access the members "name", etc, so takePrisoners has tried to offer the easiest possible interface to implement given the restrictions (a) should work with Soldier, and (b) should be possible to write other types that it also works with.

ActiveSoldier is one such other type. For reasons best known only to the author of that class, it has opted to publicly inherit from Soldier rather than providing an overloaded conversion operator. We can argue whether that's ever a good idea, but let's suppose we're stuck with it. Because it's a derived class, it is convertible to Soldier. That conversion is called a slice. Hence, if we call takePrisoners passing in the begin() and end() iterators for a vector of ActiveSoldiers, then we will slice them.

You could probably come up with similar examples for an OutputIterator, where the recipient only cares about the base class part of the objects being delivered, and so allows them to be sliced as they're written to the iterator.

The reason it's "code smell" is that we should consider (a) rewriting ActiveSoldier, and (b) changing Soldier so that it can be accessed using functions instead of member access, so that we can abstract that set of functions as an interface that other types can implement independently, so that takePrisoners doesn't have to convert to Soldier. Either of those would remove the need for a slice, and would have potential benefits for the ease with which our code can be extended in future.

[*] because it is one. The last two lines below are doing the same thing:

struct A {
int value;
A(int v) : value(v) {}
};

struct B : A {
int quantity;
B(int v, int q) : A(v), quantity(q) {}
};

int main() {
int i = 12; // an integer
B b(12, 3); // an instance of B
A a1 = b; // (1) convert B to A, also known as "slicing"
A a2 = i; // (2) convert int to A, not known as "slicing"
}

The only difference is that (1) calls A's copy constructor (that the compiler provides even though the code doesn't), whereas (2) calls A's int constructor.

As someone else said, Java doesn't do object slicing. If the code you provide were turned into Java, then no kind of object slicing would happen. Java variables are references, not objects, so the postcondition of a = b is just that the variable "a" refers to the same object as the variable "b" - changes via one reference can be seen via the other reference, and so on. They just refer to it by a different type, which is part of polymorphism. A typical analogy for this is that I might think of a person as "my brother"[**], and someone else might think of the same person as "my vicar". Same object, different interface.

You can get the Java-like effect in C++ using pointers or references:

B b(24,7);
A *a3 = &b; // No slicing - a3 is a pointer to the object b
A &a4 = b; // No slicing - a4 is a reference to (pseudonym for) the object b

[**] In point of fact, my brother is not a vicar.

C++ slicing in Java / C#

Slicing means that if you assign a subclass instance to a superclass variable, the extra information contained by subclass is "sliced" off, because the superclass variable doesn't have the extra space to store this extra information of the subclass.

This doesn't happen in Java nor with C#, because all object variables are references; when you assign a subclass instance to a superclass variable, you actually just copy the reference; the subclass object itself remains intact.



Related Topics



Leave a reply



Submit