Difficulty: Hard · Puzzle 3 of 6 · Topic: Virtual Method Puzzles
Predict what prints and explain why this is dangerous in constructor design.
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();
endConsider order: base constructor body runs before derived constructor body completes.
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: It prints `child cfg=0` (or default), because virtual dispatch reaches child method before child constructor assigns `cfg`.
Virtual calls in constructors can execute derived code on partially initialized objects.
What safer pattern would you use in UVM: explicit `build()` hook or post-construction init API?