Object Slicing
2. Object Slicing

in

When we assign Derived Object to Base object or when we instantiate Base object with Derived object, object slicing happens. In above case, only base part of Derived object will be used for assignment/creation of new object.

Example:

Derived d;
Base b = d; //Construct base from base part of derived
b = d; //Assign base part of derived to base

It also happens when we pass Derived object to a function which takes Base object, which eventually calls Copy constructor. Object slicing happens because, Base copy function (assignment) and constructor does not know anything about Derived. So, only Base part of Derived will be copied. To avoid slicing problem, we should pass pointer/references.

Tutorial posted April 11th, 2006 by girishshetty categories [ ]

Re: Object Slicing

this things is compiler dependent becuse drive
class know the base class but base class dont know the
drived class.

Re: Object Slicing

"this things is compiler dependent becuse drive
class know the base class but base class dont know the
drived class."

How does the fact that the derived class knows about the base class but the bass class not knowing about the derived class make this a compiler dependent feature?
And what do you mean by compiler dependent anyway?

Re: Object Slicing

Hi,

When an base class is assinged to its derived class the
base class takes up only the base member data leaving the
data members of derived class.this is called...

When a Derived Class object is assigned to Base class, the
base class' contents in the derived object are copied to
the base class leaving behind the derived class specific
contents. This is referred as Object Slicing.

Class Base
{
public:
int i;
};

class Derived : public Base
{
public:
int j;
};

int main()
{
Base Bobj;
Derived Dobj;
Bobj = Dobj; //Here Dobj contains both i and j.
//But only i is copied to Bobj.
}

object slicing is the phenomenon in which when we assigned
derived class with base class ,the separation of base class
data members from derived class data members occur.

thanks,

Re: Object Slicing

I know what object slicing is thanks. My question is why is this compiler dependent?