Difficulty: Hard · Puzzle 5 of 6 · Topic: String and Casting Puzzles
Why does failed cast still let code print a valid `id`?
class B; endclass
class D extends B; int id = 42; endclass
class E extends B; endclass
module p5;
B b1, b2;
D d;
initial begin
b1 = new D();
b2 = new E();
void'($cast(d, b1));
if (!$cast(d, b2))
$display("cast2 fail id=%0d", d.id);
end
endmoduleCheck what `$cast` guarantees on failure for destination variable state.
1) First cast succeeds, so `d` points to D object with id 42.
2) Second cast from E to D fails and returns 0.
3) On failed class cast, destination is unchanged, so `d` still references prior D object.
4) Therefore `d.id` is still valid and prints 42.Answer: It prints `cast2 fail id=42`
Many candidates assume failed `$cast` sets destination to null automatically.
What defensive pattern prevents stale-handle use after failed cast?