Initialization of a reference versus initialization of an object

52 views Asked by At

I know dynamic casts works on pointers and references. Both of the following work casting downwards

der d;
base& b = d;
der x = dynamic_cast<der&>(b);  -->A
der& y = dynamic_cast<der&>(b); -->B
x.method();
y.method();

I wanted to know what the difference is between A and B

1

There are 1 answers

0
R Sahu On BEST ANSWER

The line

der x = dynamic_cast<der&>(b);

constructs an object of type der and initializes it with dynamic_cast<der&>(b)

The line

der& y = dynamic_cast<der&>(b);

just initializes a reference.

x.method();

calls method() on the separately constructed object.

y.method();

calls method() on the object y references, which is d.