SystemVerilog OOP Mastery · All levels
Class Inheritance with `extends`: Code Examples
Code Examples for Class Inheritance with `extends`.
Code examples
Basic extends plus super.new constructor chain
systemverilog
class txn_base;
rand bit [31:0] addr;
function new(bit [31:0] addr = '0);
this.addr = addr;
endfunction
endclass
class burst_txn extends txn_base;
rand int unsigned beats;
function new(bit [31:0] addr = '0, int unsigned beats = 1);
super.new(addr);
this.beats = beats;
endfunction
endclass
module tb;
initial begin
burst_txn t = new(32'h1000_0040, 8);
$display("addr=%08h beats=%0d", t.addr, t.beats);
end
endmoduleThe derived constructor initializes inherited addr by explicitly calling super.new(addr). Without that call, base initialization policy can be bypassed.
Single inheritance with composition for extra capability
systemverilog
class qos_policy;
int unsigned priority;
function new(int unsigned priority = 0);
this.priority = priority;
endfunction
endclass
class packet_base;
rand bit [31:0] addr;
qos_policy qos;
function new();
qos = new(3);
endfunction
endclass
class noc_packet extends packet_base;
rand bit [7:0] vc;
function new();
super.new();
vc = 0;
endfunction
endclassThe class gets one inheritance chain (packet_base -> noc_packet) while qos behavior is attached as a composed helper object, which is the idiomatic alternative to multiple inheritance.