SystemVerilog OOP Mastery · All levels
Handles, new(), and Construction Patterns: Code Examples
Code Examples for Handles, new(), and Construction Patterns.
Code examples
Aliasing by handle assignment
systemverilog
class packet;
string name;
int unsigned size;
function new(string name = "pkt");
this.name = name;
this.size = 0;
endfunction
endclass
module alias_demo;
initial begin
packet p1 = new("tx0");
packet p2;
p2 = p1; // handle copy, same object
p2.size = 64;
$display("p1.size=%0d p2.size=%0d", p1.size, p2.size);
end
endmoduleUses constructor parameters and shows that assigning one handle to another aliases a single object.
Deep copy with clone pattern
systemverilog
class packet;
rand bit [31:0] addr;
rand bit [31:0] data;
function packet clone();
packet c = new();
c.addr = this.addr;
c.data = this.data;
return c;
endfunction
endclass
module clone_demo;
initial begin
packet src = new();
packet dst;
assert(src.randomize());
dst = src.clone();
dst.addr = 'hDEADBEEF;
$display("src.addr=%0h dst.addr=%0h", src.addr, dst.addr);
end
endmoduleShows a safe snapshot copy where later edits to dst do not mutate src.
Null-safe lazy construction helper
systemverilog
class fifo_cfg;
int unsigned depth;
function new(int unsigned depth = 16);
this.depth = depth;
endfunction
endclass
class env;
fifo_cfg cfg;
function void ensure_cfg();
if (cfg == null) cfg = new(32);
endfunction
function int unsigned get_depth();
ensure_cfg();
return cfg.depth;
endfunction
endclassDemonstrates one common pattern: guard all dereferences by ensuring construction in one place.