Note that there are some explanatory texts on larger screens.

plurals
  1. POLearning C++: returning references AND getting around slicing
    text
    copied!<p>I'm having a devil of a time understanding references. Consider the following code:</p> <pre><code>class Animal { public: virtual void makeSound() {cout &lt;&lt; "rawr" &lt;&lt; endl;} }; class Dog : public Animal { public: virtual void makeSound() {cout &lt;&lt; "bark" &lt;&lt; endl;} }; Animal* pFunc() { return new Dog(); } Animal&amp; rFunc() { return *(new Dog()); } Animal vFunc() { return Dog(); } int main() { Animal* p = pFunc(); p-&gt;makeSound(); Animal&amp; r1 = rFunc(); r1.makeSound(); Animal r2 = rFunc(); r2.makeSound(); Animal v = vFunc(); v.makeSound(); } </code></pre> <p>And the results are: "bark bark rawr rawr". </p> <p>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 <a href="https://stackoverflow.com/q/4403726/348056">previous question</a> that this difference is due to slicing and I now have a good understanding of what slicing is. </p> <p>But let's say that I want a function that returns an Animal value that is really a Dog. </p> <ol start="14"> <li>Do I understand correctly that the closest that I can get is a <em>reference</em>? </li> <li>Furthermore, is it incumbent upon the one using the rFunc interface to see that the reference returned is assign an Animal&amp;? (Or otherwise intentionally assign the reference to an Animal which, via slicing, discards polymorphism.) </li> <li>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.)</li> </ol> <hr> <p>Update: since everyone seems to agree so far that rFunc it illegitimate, that brings up another related questions: </p> <p>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.</p> <p><em>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.</em></p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload