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
SystemVerilog Class Constructor
*Click on image for a better view

  • The new operation is defined as a function with no return type
  • every class has a built-in new method, calling the constructor of class without the explicit definition of the new method will invoke the default built-in new method
  • specifying return type to the constructor shall give a compilation error (even specifying void shall give a compilation error)
  • The 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.

Class Construct
SystemVerilog Constructor for Initialization
*Click on image for a better view




Class Constructor example




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