Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to replace pointers with references in C++?
    primarykey
    data
    text
    <p>"I am sure there are tens of questions with the same title. Many of them are duplicate. Mine might be duplicate too, but I couldn't find any. So I try to make it very neat, short and simple."</p> <p>I have an hierarchy like this:</p> <pre><code>class Shape { public: virtual void virtualfunc() { std::cout &lt;&lt; "In shape\n"; } }; class Circle: public Shape { public: void virtualfunc() { std::cout &lt;&lt; "In Circle\n"; }; }; </code></pre> <p>and when I use the classes with the help of pointer, the functions are called as I expected:</p> <pre><code>int main() { Shape shape_instance; Shape* ref_shape = &amp;shape_instance ; Circle circle_instance; Circle* ref_circle = &amp;circle_instance; ref_shape = dynamic_cast&lt;Shape*&gt; (ref_circle); ref_shape-&gt;virtualfunc(); } </code></pre> <p>Here the program calls the <code>virtualfunc()</code> of the derived class and the result is naturally : <code>In Circle</code> </p> <p>Now, I want to get rid of the pointers, use references instead, and get the same result. So I make trivial modifications to <code>main()</code> to look like this: </p> <pre><code>int main() { Shape shape_instance; Shape&amp; ref_shape = shape_instance; Circle circle_instance; Circle&amp; ref_circle = circle_instance; ref_shape = dynamic_cast&lt;Shape&amp;&gt;(ref_circle); ref_shape.virtualfunc(); } </code></pre> <p>But this time, the program calls the <code>virtualfunc()</code> of the base class and the result is : <code>In Shape</code></p> <p>I appreciate if you let me know which concept of the references I am missing and how to change the references in the main() to get the result I got in the pointer version.</p> <p>thank you</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

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