I\'m having a devil of a time understanding references. Consider the following code:
class Animal
{
public:
virtual void makeSound() {cout << \"rawr\"
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.