I've been reading some OSS code lately and stumbled upon this peculiar piece:
class Foo { ..... };
void bar() {
Foo x;
Foo *y=new Foo();
x=(const Foo &) *y;
}
For the life of me I can't find documentation about the behavior of casting an object to a const reference.
Yes, you can cast the reference(object) of one (class) type to other. But, one of the two classes should inherit the other. For example, Assume we have a class with name Person with two instance variables name and age and one instance method displayPerson() which displays the name and age.
Type Casting in Java – An IntroductionType Casting is a feature in Java using which the form or type of a variable or object is cast into some other kind or Object, and the process of conversion from one type to another is called Type Casting.
You're not casting to an int, no Object can ever be cast to an int.
x=(const Foo &) *y;
is assignment. The only reason I see to explicitly cast to const reference is to have Foo::operator=(const Foo &)
called for assignment if Foo::operator=(Foo &)
also exists.
x=(const Foo &) y;
line invokes undefined behavior.
Prefer to avoid C-style casts; they are easy to get wrong. You silence the compiler, so they are too dangerous.
Edit: this answer was relevant at the time, when in the question y
was not dereferenced prior to the cast to const Foo &
. For the answer to the question after *y
edit, please see the answer given by n0rd
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With