Search code examples
c++typescasting

Is there any difference typecasting between (Parent&)child and (Parent)child in c++?


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 :)


Solution

  • 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.