-4

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

Rajeshwar
  • 11,179
  • 26
  • 86
  • 158

1 Answers1

2

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.

R Sahu
  • 204,454
  • 14
  • 159
  • 270