I'm having a devil of a time understanding references. Consider the following code:
class Animal
{
public:
virtual void makeSound() {cout << "rawr" << endl;}
};
class Dog : public Animal
{
public:
virtual void makeSound() {cout << "bark" << endl;}
};
Animal* pFunc()
{
return new Dog();
}
Animal& rFunc()
{
return *(new Dog());
}
Animal vFunc()
{
return Dog();
}
int main()
{
Animal* p = pFunc();
p->makeSound();
Animal& r1 = rFunc();
r1.makeSound();
Animal r2 = rFunc();
r2.makeSound();
Animal v = vFunc();
v.makeSound();
}
And the results are: "bark bark rawr rawr".
In a Java way of thinking, (which has apparently corrupted my conceptualization of C++), the results would be "bark bark bark bark". I understand from my previous question that this difference is due to slicing and I now have a good understanding of what slicing is.
But let's say that I want a function that returns an Animal value that is really a Dog.
- Do I understand correctly that the closest that I can get is a reference?
- Furthermore, is it incumbent upon the one using the rFunc interface to see that the reference returned is assign an Animal&? (Or otherwise intentionally assign the reference to an Animal which, via slicing, discards polymorphism.)
- How on earth am I supposed to return a reference to a newly generated object without doing the stupid thing I did above in rFunc? (At least I've heard this is stupid.)
Update: since everyone seems to agree so far that rFunc it illegitimate, that brings up another related questions:
If I pass back a pointer how do I communicate to the programmer that the pointer is not theirs to delete if this is the case? Or alternatively how do I communicate that the pointer is subject to deletion at any time (from the same thread but a different function) so that the calling function should not store it, if this is the case. Is the only way to communicate this through comments? That seems sloppy.
Note: All this is leading up to an idea for a templated shared_pimpl concept I was working on. Hopefully I'll learn enough to post something about that in a couple of days.