简体   繁体   中英

Will this result in object slicing?

Say I have an array of pointers to an abstract class:

Piece *pieces[2]; // where piece is an abstract class

And I have two classes that extend Piece called King and Queen . I assign a King to a spot in pieces and Queen to another spot:

pieces[0] = new King();
pieces[1] = new Queen();

If I haven't overloaded the assignment operator, does slicing occur? Or does pieces[0] is an instance of King and pieces[1] is an instance of Queen ? What is going on in that array (if this was C++)?

EDIT: See a full example of the code in question here .

This doesn't actually compile: you can't assign a King * (the type of the expression new King ) to a Piece (the type of the expression *pieces[0] ).

To answer your implied question, though:

Piece *piece = new King(); // fine, no slicing, just assigning a pointer
*piece = Queen();          // oops, slicing - assigning a Queen to a Piece

In the array in your question, assuming you'd written pieces[0] = new King; , etc., you'd just be storing two Piece pointers, one of which points to a King and one of which points to a Queen .

No slicing will occur. You're doing pointer assignment, not object assignment.

Yes slicing will occur.

Slicing will always occur whenever you are trying to put derived class object to any of its base class. This slicing will become visible if your derived class has added some functionality that your base class do not provide.

Remember, this is the case when you are not following OOP principals. Principal says,

"When you are deriving from any class you should not change the interface. 
The reason for inheritance is moving from generic to specific type, and not
 providing new functionality."

And, if you follow this principal then slicing behaviour can be defined as,

“Moving from specific behaviour to more general behaviour”. 

Slicing through pointer objects are temporary and you can cast the pointer back to derived class to get the original behaviour. Slicing through the object is permanent.

NOTE:- Slicing always does not happen in case of private inheritance. 
If you try to do so it will result in compilation error.
(For more information on private inheritance:-http://stackoverflow.com/questions/19075517/object-slicing-in-private-inheritance/19083420?noredirect=1#19083420)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM