SystemVerilog OOP Mastery · All levels
Classes and Objects: Code Examples
Code Examples for Classes and Objects.
Code examples
Declaring a handle versus constructing an object
systemverilog
class packet;
rand bit [31:0] addr;
rand bit [31:0] data;
endclass
module demo;
initial begin
packet p; // handle only, currently null
if (p == null) $display("p is null before new");
p = new(); // object allocated now
assert(p.randomize());
$display("addr=%0h data=%0h", p.addr, p.data);
end
endmoduleShows the exact transition from null handle to allocated object, then randomization on a valid object.
Independent objects from same class type
systemverilog
class txn;
rand bit [7:0] id;
endclass
module demo2;
initial begin
txn t1 = new();
txn t2 = new();
t1.id = 8'hA5;
t2.id = 8'h3C;
$display("t1.id=%0h t2.id=%0h", t1.id, t2.id);
end
endmoduleDemonstrates that two handles constructed with separate new() calls point to distinct objects.
Centralized object creation helper
systemverilog
class packet;
rand int unsigned length;
function void post_randomize();
if (length == 0) length = 1;
endfunction
endclass
function packet make_packet();
packet p = new();
assert(p.randomize() with { length inside {[1:64]}; });
return p;
endfunctionEncapsulates allocation plus initialization so callers never touch uninitialized handles.