C++ Blog

Saturday, October 08, 2005

What is “Slicing Problem”?

class base {}
class derived: public base {}

class base baseObj;
class derived derivedObj;

baseObj = derivedObj;
/* Only baseObj features will be copied leaving all the extra features in derivedObj this is called slicing */

derivedObj = baseObj;
/* Down slicing only baseObj features will copied and all the others will have unknown values, this is not safe to do this and C++ provides an casting operator for doing this, it is called as dynamic_cast */

Pass by Reference

There will not be any splicing if we pass by reference. Slicing normally happens when one object is assigned to another. If we pass a value by reference then there is no assignment that is taking place and the objects themselves get passed as an argument. So there will be no slicing.

Slicing is not related to pointers or members, it is related with objects themselves.

0 Comments:

Post a Comment

<< Home