Difficulty: Easy · Puzzle 1 of 6 · Topic: Parameterized Class Puzzles
Predict all printed `gid/lid` pairs and explain which counters are shared across `T` specializations.
class id_bank;
static int global_id = 0;
endclass
class bucket #(type T = int) extends id_bank;
static int local_id = 0;
int gid;
int lid;
function new();
gid = global_id;
global_id = global_id + 1;
lid = local_id;
local_id = local_id + 1;
endfunction
endclass
initial begin
bucket#(int) a = new();
bucket#(int) b = new();
bucket#(byte) c = new();
bucket#(byte) d = new();
$display("a gid/lid=%0d/%0d", a.gid, a.lid);
$display("b gid/lid=%0d/%0d", b.gid, b.lid);
$display("c gid/lid=%0d/%0d", c.gid, c.lid);
$display("d gid/lid=%0d/%0d", d.gid, d.lid);
endTrack where each static is declared, not where constructor executes.
1) `global_id` lives in non-parameterized `id_bank`, so all specializations share it: gids become 0,1,2,3.
2) `local_id` lives in `bucket#(T)`, so each specialization has its own static instance.
3) `bucket#(int)` lids are 0,1 and `bucket#(byte)` lids restart at 0,1.Answer: Printed gids are 0/1/2/3 globally; lids are 0,1 for `int` and 0,1 for `byte` separately.
Checked by running the code in Verilator 5; the printed output supports the answer above. The shown code run in Verilator: the base-class static is shared, the per-specialization static restarts for each type.
Candidates often memorize 'statics are global' without considering parameterized specialization boundaries.
How would behavior change if `global_id` moved inside `bucket#(T)`? Model answer: it would become per-specialization like `local_id`, so the gids would restart for each type and print 0/1 for `int` and 0/1 for `byte` instead of 0/1/2/3.
The global ids print 0, 1, 2, 3, and the local ids are 0, 1 for int and 0, 1 again for byte. The global counter lives in a non-parameterized class, so all specializations share it. The local counter lives in the parameterized class, so each specialization gets its own copy. The trap is assuming a static in a parameterized class is shared across all parameter values, so I would check where each static is declared.