SystemVerilog OOP Mastery · All levels
Abstract Classes with `virtual class`: Code Examples
Code Examples for Abstract Classes with `virtual class`.
Code examples
Virtual base with reusable fields and methods
systemverilog
virtual class packet_base;
rand bit [31:0] addr;
rand bit [31:0] data;
function void print();
$display("addr=%08h data=%08h", addr, data);
endfunction
endclass
class axi_packet extends packet_base;
rand bit [1:0] burst;
endclass
module demo;
initial begin
axi_packet p = new();
p.addr = 'h1000_0040;
p.data = 'hDEAD_BEEF;
p.print();
end
endmoduleThe base class is abstract because of `virtual class`, but it still contributes real implementation. Concrete subclasses such as `axi_packet` are legal to construct.
Abstract base can enforce specialization points
systemverilog
virtual class scoreboard_base;
int unsigned checks;
pure virtual function bit compare(bit [7:0] exp, bit [7:0] got);
function void note_result(bit pass);
checks++;
if (!pass) $display("Mismatch at check %0d", checks);
endfunction
endclass
class exact_scoreboard extends scoreboard_base;
virtual function bit compare(bit [7:0] exp, bit [7:0] got);
return (exp == got);
endfunction
endclassThe base class owns shared bookkeeping (`checks` and `note_result`) while forcing each derived scoreboard to provide protocol-specific compare semantics.