Tutorials

Learn More

Parameterized classes are useful when the same class needs to be instantiated differently. The default parameter can be set in the class definition. These parameters can be overridden when it is instantiated.

The parameter can be constant values and data types.

Parameterized class example

In the below example, WIDTH = 2 and data_type = bit [2:0] are default parameters for transaction class.

There are two objects created. Object tr1 uses default parameters while tr2 uses WIDTH = 3 and data type = int as parameters.

An example shows that parameter values can be replaced during instantiation.

transaction tr1;  // Default parameters are used i.e. WIDTH = 2 and D_TYPE = bit [2:0]
transaction #(3, int) tr2;  // Default parameters are overridden with mentioned value. WIDTH = 3 and D_TYPE = int

For tr1 object, default parameters WIDTH = 2 and type D_TYPE = bit [2:0] are not enough to store data = 7 and id = 15, so it is expected to get incorrect values on the calling display() function.

For tr2, default parameters are overridden with WIDTH = 3 and D_TYPE = int to accommodate data = 7 and id = 15. So, it is expected to get assigned values on calling display() function 

Data-type can be passed as a parameter.

class transaction #(parameter WIDTH = 2, type D_TYPE = bit [2:0]);
  bit [WIDTH-1:0] data;
  D_TYPE id;
  
  function void display();
    $display("data = %0d, id = %0d", data, id);
  endfunction
endclass

module class_example;
  transaction tr1;
  transaction #(3,int) tr2;
  
  initial begin
    tr1 = new();
    tr2 = new();
    
    tr1.data = 7;
    tr1.id = 15;
    tr1.display();
    
    tr2.data = 7;
    tr2.id = 15;
    tr2.display();
  end
endmodule

Output:

data = 3, id = 7
data = 7, id = 15

Example for parameterized class with class data type as a parameter

The class err_trans is used as one of the parameters for the class transaction.

class err_trans;
  bit [31:0] err_data;
  bit error;
endclass
  
class transaction #(parameter WIDTH = 32, type D_TYPE = err_trans);
  bit [WIDTH-1:0] data;
  D_TYPE err_tr;
  
  function void display();
    $display("transaction: data = %0d", data);
    $display("err_trans: err_data = %0h and error = %0d", err_tr.err_data, err_tr.error);
  endfunction
endclass

module class_example;
  transaction tr;
  
  initial begin
    tr = new();
    tr.err_tr = new();
    
    tr.data = 100;
    tr.err_tr.err_data = 32'hFFFF_FFFF;
    tr.err_tr.error = 1;
    
    tr.display();
  end
endmodule

Output:

transaction: data = 100
err_trans: err_data = ffffffff and error = 1

System Verilog Tutorials