what is object slicing?

Answer Posted / chris pearson

"Object slicing" is an informal term that is often used (as
in all the answers above) to indicate that (in some
languages, usually C++) assignment to a superclass instance
from a subclass instance does not copy the member variables
defined only in the subclass.

This usage of the term is inapt and misleading, for several
reasons:

1. The notion that an object has been damaged ("sliced")
suggests something to be avoided. However, it is not
possible (or meaningful) in any statically typed language
for a superclass instance to contain subclass member
variables, so in fact assignment to a superclass operates
correctly and is a useful language feature.

2. After such an assignment, the source, subclass, object
remains unchanged, so it has in no sense been been "sliced".

3. After such an assignment, all member variables of the
destination, superclass, object are present and have been
assigned values, so neither has it in any sense
been "sliced".

The case to which the term "object slicing" is better
applied is more subtle and problematic. It occurs in a
statically typed language such as C++ where assignment
appears to be to a superclass instance but is actually to a
subclass instance.

For example:

void myassign(mysuperclass &dest)
{
mysuperclass source;
dest = source;
}

mysubclass sub;
myassign(sub); // assigns only superclass members of
sub!

A better term for this case might be "partial assignment".

Such partial assignment is not possible in Java because
that language only allows object references, and assignment
to a reference simply causes it to refer to a different
object.

-- Chris

Is This Answer Correct ?    9 Yes 2 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

Give an example where we have to specifically use C programming language and C++ programming language cannot be used?

1152


How do you explain polymorphism?

598


Why can't we have instance(stack) of a class as a member of the same class like eg.Class A{A obj;} as we can have self refential pointer

1625


What is oops in simple words?

585


What is constructor in oop?

591






What is a null tree?

632


When not to use object oriented programming?

572


What does no cap mean?

593


What is advantage of inheritance?

694


What is class and object in oops?

615


What is the advantage of oop over procedural language?

630


Which type does string inherit from?

618


What is abstract class in oop?

538


What are the two different types of polymorphism?

677


what are the different types of qualifier in java?

1847