Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting an object to a reference?

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.

like image 740
Afiefh Avatar asked May 07 '11 20:05

Afiefh


People also ask

Can you cast a 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.

Can you cast an object in Java?

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.

Can we just cast the reference to an int?

You're not casting to an int, no Object can ever be cast to an int.


2 Answers

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.

like image 80
n0rd Avatar answered Sep 28 '22 11:09

n0rd


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

like image 32
usta Avatar answered Sep 28 '22 10:09

usta