add2c
add2c

Reputation: 99

Pass by reference avoids object slicing

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.

Upvotes: 5

Views: 2012

Answers (1)

juanchopanza
juanchopanza

Reputation: 227458

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.

Upvotes: 12

Related Questions