SystemVerilog Class Assignment

Class Assignment

Object will be created only after doing new to an class handle,

 packet   pkt_1;
 pkt_1  = new();
 packet   pkt_2;
 pkt_2  = pkt_1;

In the above piece of code,

  • an object is created only for pkt_1, pkt_2 is just a handle to the packet
  • pkt_1 is assigned to the pkt_2. so only one object has been created, pkt_1 and pkt_2 are two handles both are pointing to the same object
  • As both the handles are pointing to the same object any changes made with respect to pkt_1 will reflect on pkt_2
SystemVerilog Class Assignment
SystemVerilog Class Assignment

Class assignment example

The below example shows an assigning the object handle to another handle and accessing class properties with it.

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 properties
  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 class_assignment;
  packet pkt_1;
  packet pkt_2;

  initial begin
    pkt_1 = new();
    $display("\t****  calling pkt_1 display  ****");
    pkt_1.display();
    //assigning pkt_1 to pkt_2
    pkt_2 = pkt_1;
    $display("\t****  calling pkt_2 display  ****");
    pkt_2.display();
    //changing values with pkt_2 handle
    pkt_2.addr = 32'hAB;
    pkt_2.pkt_type = "BAD_PKT";

    //changes made with pkt_2 handle will reflect on pkt_1
    $display("\t****  calling pkt_1 display  ****");
    pkt_1.display();
  end
endmodule

Simulator Output

 ****calling pkt_1 display****
---------------------------------------------------------
addr = 16
data = ff
write = 1
pkt_type = GOOD_PKT
---------------------------------------------------------
****calling pkt_2 display****
---------------------------------------------------------
addr = 16
data = ff
write = 1
pkt_type = GOOD_PKT
---------------------------------------------------------
****calling pkt_1 display****
---------------------------------------------------------
addr = 171
data = ff
write = 1
pkt_type = BAD_PKT
---------------------------------------------------------

Click to execute on

❮ Previous Next ❯