Friday, May 30, 2008

What is object slicing?

  • Object slicing is a concept where additional attributes of a derived class object is sliced to form a base class object.
  • Object slicing doesn't occur when pointers or references to objects are passed as function arguments since both the pointers are of the same size.
  • Object slicing will be noticed when pass by value is done for a derived class object for a function accepting base class object.
  • Object slicing could be prevented by making the base class function pure virtual there by disallowing object creation.

Demonstrate the concept of object slicing

#include <iostream>
using namespace std;

class Base {
        int data1;
        int data2;
    public:
        Base(int a, int b) {
            data1 = a;
            data2 = b;
        }

        virtual void display() {
            cout << "I am Base class" << endl;
        }
};

class Derived : public Base {
        int data3;
    public:
        Derived(int a, int b, int c) : Base(a, b) {
            data3 = c;
        }

        void display() {
            cout << "I am Derived class" << endl;
        }
};

void somefunc ( Base obj )
{
    obj.display();
}

int main()
{
    Base b(10, 20);
    Derived d(100, 200, 300);

    somefunc(b);
    somefunc(d);
}
OUTPUT:
I am Base class
I am Base class

15 comments :

  1. The definition is absolutely correct and to the point. Thanks a lot for the example as well.

    ReplyDelete
  2. this is good article ... an example for how to avoid object slicing can also be added..

    ReplyDelete
  3. Can You please tell me when to use this feature in your program.
    one use I can guess is to initialize the base class object.
    Please tell me the practical usages.

    Thanks
    -Avinash

    ReplyDelete
  4. Very good explanation, Thanks. - Dinesh

    ReplyDelete
  5. BUT THIS DOESN'T CLEAR THE slicing of Data mambers of"derived class" when it's object is been holded by base class,is done as here we saw a function only......may be i am wrong but didn't got how "datac" is going to Base's scope?

    ReplyDelete
  6. why u used virtual keyword in base class

    ReplyDelete
  7. Can you also tell and give example for Composition, aggregation would be helpful

    ReplyDelete
  8. It is explained in simple words so it is easily understood

    ReplyDelete
  9. It is explained in simple words so it is easily understood

    ReplyDelete
  10. very useful. I learned from this blog.

    ReplyDelete
  11. it is useful example for object slicing.
    good job...

    ReplyDelete
  12. very usefull, but also provide how to avoid object slicing

    ReplyDelete
  13. I am not getting where exactly the object slicing occured and where u assigned the derived class object to base object where the problem of object slicing really arises.......

    ReplyDelete

Contact Form

Name

Email *

Message *

Back to Top