Learning C++: returning references AND getting around slicing

前端 未结 8 1372
醉酒成梦
醉酒成梦 2021-02-14 00:06

I\'m having a devil of a time understanding references. Consider the following code:

class Animal
{
public:
    virtual void makeSound() {cout << \"rawr\"         


        
8条回答
  •  有刺的猬
    2021-02-14 00:18

    In order to avoid slicing you have to return or pass around a pointer to the object. (Note that a reference is basically a 'permanently dereferenced pointer'.

    Animal r2 = rFunc();
    r2.makeSound();
    

    Here, r2 is ting instantiated (using the compiler generated copy ctor) but it's leaving off the Dog parts. If you do it like this the slicing won't occur:

    Animal& r2 = rFunc();
    

    However your vFunc() function slices inside the method itself.

    I'll also mention this function:

    Animal& rFunc()
    {
        return *(new Dog());
    }
    

    It's weird and unsafe; you're creating a reference to a temporary unnamed variable (dereferenced Dog). It's more appropriate to return the pointer. Returning references is normally used to return member variables and so on.

提交回复
热议问题