VLSI DV Interview Puzzles · All levels

Failed Class Cast Leaves Old Handle

Why does failed cast still let code print a valid `id`?

Puzzle

Difficulty: Hard · Puzzle 5 of 6 · Topic: String and Casting Puzzles

Why does failed cast still let code print a valid `id`?

Code

systemverilog
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
endmodule

Hint

Check what `$cast` guarantees on failure for destination variable state.

Step-by-step solution

diagram
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

Answer: It prints `cast2 fail id=42`

Why candidates get it wrong

Many candidates assume failed `$cast` sets destination to null automatically.

Interviewer follow-up

What defensive pattern prevents stale-handle use after failed cast?

Related topics