Difficulty: Medium · Puzzle 2 of 6 · Topic: Parameterized Class Puzzles
Do these two handles share the same static counter or maintain two counters?
class pkt #(int W = 8);
static int created = 0;
function new();
created++;
endfunction
endclass
typedef pkt#(32) pkt32_t;
initial begin
pkt#(32) a;
pkt32_t b;
a = new();
b = new();
$display("pkt#(32)::created=%0d", pkt#(32)::created);
$display("pkt32_t::created=%0d", pkt32_t::created);
endA typedef alias does not create a new specialization.
1) `pkt32_t` is only an alias for exactly `pkt#(32)`.
2) Both objects increment the same specialization static `created`.
3) Both displays print 2.Answer: They share one counter; both lines print 2 because typedef alias points to same specialization.
Checked by running the code in Verilator 5; the printed output supports the answer above. The shown code run in Verilator: a typedef alias is the same specialization and shares one static.
Mistaking typedef for a new derived type causes wrong assumptions about static sharing. Note the construction is written as separate statements inside `initial`: with declaration initialisers (`pkt#(32) a = new();`) the order of those initialisers against the class static `created = 0` is not fixed by the LRM, and Verilator 5.048 printed `0 0` for that form. Assigning `a = new(); b = new();` in the body gives 2 and 2 in every tool.
Would `pkt#(16)::created` change in this snippet? Model answer: no, it stays 0. `pkt#(16)` is a different specialization with its own static, and no `pkt#(16)` object was constructed.
They share one counter, and both lines print 2. A typedef is only an alias for the same specialization, so there is only one class and one static created variable. The trap is thinking the alias creates a separate type. I would check that the parameter values are identical, because only identical values give the same specialization.