VLSI DV Interview Puzzles · All levels

Virtual Call from Base Constructor

Predict what prints and explain why this is dangerous in constructor design.

Puzzle

Difficulty: Hard · Puzzle 3 of 6 · Topic: Virtual Method Puzzles

Predict what prints and explain why this is dangerous in constructor design.

Code

systemverilog
class base;
  function new();
    init();
  endfunction
  virtual function void init();
    $display("base init");
  endfunction
endclass

class child extends base;
  int cfg;
  function new();
    super.new();
    cfg = 32'hCAFE;
  endfunction
  function void init();
    $display("child cfg=%0h", cfg);
  endfunction
endclass

initial begin
  child c = new();
end

Hint

Consider order: base constructor body runs before derived constructor body completes.

Step-by-step solution

diagram
1) `super.new()` enters base constructor, which calls virtual `init()`.
2) Runtime object is `child`, so dynamic dispatch chooses `child::init()`.
3) `cfg` has not been assigned `32'hCAFE` yet, so print shows default value (typically 0).
4) Avoid virtual callbacks from constructors unless derived state is guaranteed initialized.

Answer

Answer: It prints `child cfg=0` (or default), because virtual dispatch reaches child method before child constructor assigns `cfg`.

Why candidates get it wrong

Virtual calls in constructors can execute derived code on partially initialized objects.

Interviewer follow-up

What safer pattern would you use in UVM: explicit `build()` hook or post-construction init API?

Related topics