Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass by reference avoids object slicing

Tags:

c++

class Pet {
public:
    virtual string getDescription() const {
        return "This is Pet class";
    }
};

class Dog : public Pet {
public:
    virtual string getDescription() const {
        return "This is Dog class";
    }
};

suppose i have a function which takes argument of bas class type like

void describe(Base obj) {
   p.getDescription();
}

and i pass derived class object in this function, so the object will be sliced and we ll get output rerlated to base class.

But if i modify this function and make it like

void describe(Base& obj) {
   p.getDescription();
}

and again passes derived class object, this time output will be of derived class.

I couldnt understand how pass by reference avoides object slicing.

like image 581
add2c Avatar asked Mar 10 '15 07:03

add2c


People also ask

How do you prevent object slices?

Object slicing can be prevented by making the base class function pure virtual thereby disallowing object creation. It is not possible to create the object of a class that contains a pure virtual method.

What is object slicing and how can we prevent it?

Object slicing happens when a derived class object is assigned to a base class object, additional attributes of a derived class object are sliced off to form the base class object. We can avoid above unexpected behavior with the use of pointers or references.

What is meant by object slicing?

Object slicing is used to describe the situation when you assign an object of a derived class to an instance of a base class. This causes a loss of methods and member variables for the derived class object. This is termed as information being sliced away.

What is object slicing explain object slicing in context of Upcasting in Java?

Object slicing is defined as the conversion of an object into something with less information (typically a superclass). In C++ it occurs when an object is passed by value and copying the parameter value results in an upcast and it is considered a bad thing, as it may result in very subtle bugs.


1 Answers

The derived object gets "sliced" when it is used to instantiate a base class object. This happens when you pass by value, because the function parameter is a base class object, not anything else. It is the equivalent of doing this:

Derived d;
Base b = d; // b is a Base, not a Derived. It knows nothing of Derived.

A reference is simply an alias for an object, so a reference to a Base object does not involve the construction of a new Base object. It simply aliases one:

Base& b = d; // b aliases d, i.e. a Derived object

After the above statement, b is an alias for d and can be use to access d's Base interface polymorphically. It can alias a Derived object because Derived is-a Base. This wouldn't be possible with, say, private inheritance.

like image 68
juanchopanza Avatar answered Sep 30 '22 03:09

juanchopanza