How to replace pointers with references in C++?

c++, pointers, reference

Solution

References cannot be reseated. Once you initialize the reference in the initialization, it becomes an alias to the referred object and cannot be distinguished from it. The latter assignment:

ref_shape = dynamic_cast<Shape&>(ref_circle);

really means:

shape_instance = dynamic_cast<Shape&>(ref_circle);

You can, on the other hand, bind a new reference to the object (and you don't need the `dynamic_cast`, as the conversion from reference to derived to reference to base is implicit):

Shape & another_ref = ref_circle;
another_ref.virtualfunc();          // Dispatches to Circle::virtualfunc

Problem

"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." I have an hierarchy like this: ``` class Shape { public: virtual void virtualfunc() { std::cout << "In shape\n"; } }; class Circle: public Shape { public: void virtualfunc() { std::cout << "In Circle\n"; }; }; ``` and when I use the classes with the help of pointer, the functions are called as I expected: ``` int main() { Shape shape_instance; Shape* ref_shape = &shape_instance ; Circle circle_instance; Circle* ref_circle = &circle_instance; ref_shape = dynamic_cast<Shape*> (ref_circle); ref_shape->virtualfunc(); } ``` Here the program calls the `virtualfunc()` of the derived class and the result is naturally : `In Circle` Now, I want to get rid of the pointers, use references instead, and get the same result. So I make trivial modifications to `main()` to look like this: ``` int main() { Shape shape_instance; Shape& ref_shape = shape_instance; Circle circle_instance; Circle& ref_circle = circle_instance; ref_shape = dynamic_cast<Shape&>(ref_circle); ref_shape.virtualfunc(); } ``` But this time, the program calls the `virtualfunc()` of the base class and the result is : `In Shape` 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. thank you

Original source