Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

Inheritance: Why the Handle's Type Matters (Without virtual)

SystemVerilog Classes & OOP

Runnable example from the SystemVerilog Inheritance tutorial (Why the Handle's Type Matters (Without virtual))

Open in IDE
design.sv
class Packet;
   int addr;

   function new (int addr);
      this.addr = addr;
   endfunction

	function display ();
		$display ("[Base] addr=0x%0h", addr);
	endfunction
endclass

// A subclass called 'ExtPacket' is derived from the base class 'Packet' using
// 'extends' keyword which makes 'ExtPacket' a child of the parent class 'Packet'
// The child class inherits all variables and methods from the parent class
class ExtPacket extends Packet;

	// This is a new variable only available in child class
	int data;

   function new (int addr, data);
      super.new (addr); 	// Calls 'new' method of parent class
      this.data = data;
   endfunction

	function display ();
		$display ("[Child] addr=0x%0h data=0x%0h", addr, data);
	endfunction
endclass
testbench.sv
module tb;
	Packet      p;
	ExtPacket   sc;

	initial begin
        sc = new (32'hfeed_feed, 32'h1234_5678);

        // p is declared as type Packet, but now points to the SAME
        // ExtPacket object that sc points to
        p = sc;

        p.display ();
	end
endmodule
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.