1

I was just implementing a function and I recognized that there was an error (type error) when a variable was typecasted as (Parent)child. But the error fixed when it was typecasted as (Parent&)child. Then I checked the type of the variables typecasted and both are same type. Is there a difference or is it probably just because of my code?

Thanks in advance :)

myanar7
  • 13
  • 7
  • please provide a [mcve]. `(Parent)child` is most likely object slicing: https://stackoverflow.com/questions/274626/what-is-object-slicing. What actually happens in your code one can only say when seeing the code – 463035818_is_not_an_ai Jan 15 '22 at 12:35

1 Answers1

5

Yes, there is a difference. Casting to an object produces a new prvalue. Casting to a reference produces an lvalue that refers to the base sub object.

P.S. Prefer using C++ style casts (static_cast) instead of C-style casts.

eerorika
  • 232,697
  • 12
  • 197
  • 326
  • 3
    i doubt that this will actually help op, but its an accurate answer to the question they asked ;) – 463035818_is_not_an_ai Jan 15 '22 at 12:39
  • 1
    @463035818_is_not_a_number I believe that in addition to being an accurate answer to what they asked, this will also help OP to ask the question that they may have been looking for. – eerorika Jan 15 '22 at 15:57