SystemVerilog Class Constructors

 Class Constructors 


The new function is called as class constructor.
On calling the new method it allocates the memory and returns the address to the class handle.

SystemVerilog Class Constructor


  • The new operation is defined as function with no return type
  • every class has built-in new method, calling the constructor of class without the explicit definition of new method will invoke the default built-in new method
  • specifying return type to the constructor shall give an compilation error (even specifying void shall give an compilation error)
  • Constructor can be used for initializing the class properties. In case of any initialization required, those can be placed in the constructor and It is also possible to pass arguments to the constructor, which allows run-time customization of an object.
SystemVerilog Constructor for Initialization

 Example-1:  

class packet;
  //class properties
  bit [31:0] addr;
  bit [31:0] data;
  bit  write;
  string pkt_type;
  //constructor
  function new();
    addr  = 32'h10;
    data  = 32'hFF;
    write = 1;
    pkt_type = "GOOD_PKT";
  endfunction

  //method to display class prperties
  function void display();
    $display("---------------------------------------------------------");
    $display("\t addr  = %0d",addr);
    $display("\t data  = %0h",data);
    $display("\t write = %0d",write);
    $display("\t pkt_type  = %0s",pkt_type);
    $display("---------------------------------------------------------");
  endfunction
endclass

module sv_constructor;
  packet pkt;
  initial begin
    pkt = new();
    pkt.display();
  end
endmodule


 Simulator Output  
addr = 16
data = ff
write = 1
pkt_type = GOOD_PKT
Execute the above code on