Can C++ slicing apply to other languages too, like Java/C#?
Asked
Active
Viewed 2,678 times
7
-
1This is not an exact duplicate. The supposed duplicate asks nothing about C# or Java. – Rob Kennedy Feb 12 '09 at 00:36
-
This is a duplicate. See [What is the slicing problem in C++?](http://stackoverflow.com/questions/274626). – codelogic Feb 11 '09 at 10:40
-
Raj, buy a copy of Scott Meyer's excellent book "Effective C++" ([sanitised Amazon link](http://www.amazon.com/dp/0321334876/)) for many excellent discussions about this problem and many other C++ gotchas. HTH cheers, – Rob Wells Feb 11 '09 at 10:44
1 Answers
15
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.

Joonas Pulakka
- 36,252
- 29
- 106
- 169
-
My terminology was a bit off (corrected it now), but I think my point wasn't. If I'm still quite incorrect, could you please correct. – Joonas Pulakka Feb 11 '09 at 13:45
-
1
-
C# has value types. i think in c# your statement isn't true (? i'm a c# noob. so i can be wrong here), but for java it's of course very true. – Johannes Schaub - litb Feb 11 '09 at 14:28
-
ah never mentioned. you can't derive a struct from another struct in C# – Johannes Schaub - litb Feb 11 '09 at 14:37
-
You're right. My statement was incorrect regarding C# value types -that is, structs. For classes it's still correct. – Joonas Pulakka Feb 11 '09 at 14:42
-
-
just one thing: duffymo, your comment was useless :D and i now see you said "subclass" so i guess that would already rule out structs :) i should have read more closely. i'm sorry mad-j. anyway i will +1 this one :) – Johannes Schaub - litb Feb 11 '09 at 14:45
-
My point is that slicing happens in both Java and C#. The OP said it doesn't happen. Either I've misunderstood the question or the OP has. – duffymo Feb 11 '09 at 15:26
-
In Java if you assign a subclass to a superclass var you can grab the subclass' data if you cast the superclass to the subclass. It's not removed. e.g. Inner i = new Inner(5); Outer o = i; System.out.println((Inner)o.getValFromInnerConstructorArg()); I think gives: 5 – Rob Grant Feb 11 '09 at 16:33
-
duffymo, can you give an example of object slicing happening in Java? I don't understand how it could happen, since objects are automatically allocated the memory that they need. The memory allocation is not affected by the type of the reference variable. – Joonas Pulakka Feb 11 '09 at 17:21