Play and learn 300 000+ tabs online

Friday, June 4, 2010

C++ Object Slicing

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. Here the derived class data will not store in the base class object as the container has no members of derived class members.

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.
}

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.