Can C++ slicing apply to other languages too, like Java/C#?
- <strike>This is a duplicate</strike>. See What is the slicing problem in C++?.codelogic– codelogic2009-02-11 10:40:40 +00:00Commented Feb 11, 2009 at 10:40
- Raj, buy a copy of Scott Meyer's excellent book "Effective C++" (sanitised Amazon link) for many excellent discussions about this problem and many other C++ gotchas. HTH cheers,Rob Wells– Rob Wells2009-02-11 10:44:33 +00:00Commented Feb 11, 2009 at 10:44
- 1This is not an exact duplicate. The supposed duplicate asks nothing about C# or Java.Rob Kennedy– Rob Kennedy2009-02-12 00:36:53 +00:00Commented Feb 12, 2009 at 0:36
Add a comment |
1 Answer
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.
10 Comments
Joonas Pulakka
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.
Rob Kennedy
Your comment wasn't very helpful, Duffymo.
Johannes Schaub - litb
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
ah never mentioned. you can't derive a struct from another struct in C#
Joonas Pulakka
You're right. My statement was incorrect regarding C# value types -that is, structs. For classes it's still correct.
|