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

When Class Constructor Is Explicity Defined

SystemVerilog Classes & OOP

A user-defined new() initializes a member, so the object already holds that value when it is read right after new.

Open in IDE
testbench.sv
// Define a class called "Packet" with a 32-bit variable to store address
// Initialize "addr" to 32'hfade_cafe in the new function, also called constructor
class Packet;
  bit [31:0] addr;
 
  function new ();
    addr = 32'hfade_cafe;
  endfunction
endclass
 
module tb;
  
  // Create a class handle called "pkt" and instantiate the class object
  initial begin
    // The class's constructor new() fn is called when the object is instantiated
    Packet pkt = new;   
    
    // Display the class variable - Because constructor was called during 
    // instantiation, this variable is expected to have 32'hfade_cafe;
    $display ("addr=0x%0h", pkt.addr);
  end
endmodule

/* 
Simulation Log:
---------------
ncsim> run
addr=0xfadecafe
ncsim: *W,RNQUIE: Simulation is complete.
ncsim> exit
*/
design.sv
// Code your design here
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.