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

add2c
  • 89
  • 1
  • 9
  • 3
    While not strictly true, a reference is basically just a fancy pointer.So when you pass a reference, you really pass a pointer to the *actual* object. – Some programmer dude Mar 10 '15 at 07:05
  • 1
    Aren't you really just asking what the slicing problem is? –  Mar 10 '15 at 07:19
  • No, I know the object slicing concept. I got confused in pass by refernece but now got the answer :) – add2c Mar 10 '15 at 07:22
  • possible duplicate of [What is object slicing?](http://stackoverflow.com/questions/274626/what-is-object-slicing) –  Mar 10 '15 at 07:47
  • it is related to pass by reference.. – add2c Mar 10 '15 at 08:38

1 Answers1

12

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.

juanchopanza
  • 223,364
  • 34
  • 402
  • 480