SystemVerilog class this keyword

 " this " keyword 



The this keyword is used to refer to class properties.
below example shows the advantage of "this" keyword.


 Example -1 



In the example below,
The addr, data,write and pkt_type are property of both class and an argument to the function new, as the name in both are same.this will lead to an ambiguity in assignment and values will not be assigned properly.

class packet;
  //class properties
  bit [31:0] addr;
  bit [31:0] data;
  bit        write;
  string     pkt_type;

  //constructor
  function new(bit [31:0] addr,data,bit write,string pkt_type);
    addr  = addr;
    data  = data;
    write = write;
    pkt_type = pkt_type;
  endfunction

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

module sv_constructor;
  packet pkt;
  initial begin
    pkt = new(32'h10,32'hFF,1,"GOOD_PKT");
    pkt.display();
  end
endmodule


 Simulator Output  
addr = 0
data = 0
write = 0
pkt_type =
Execute the above code on 

 Example -2 


the above problem can be overcome by using "this" keyword to the class properties.

class packet;
  //class properties
  bit [31:0] addr;
  bit [31:0] data;
  bit        write;
  string     pkt_type;
  //constructor
  function new(bit [31:0] addr,data,bit write,string pkt_type);
    this.addr  = addr;
    this.data  = data;
    this.write = write;
    this.pkt_type = pkt_type;
  endfunction

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

module sv_constructor;
  packet pkt;
  initial begin
    pkt = new(32'h10,32'hFF,1,"GOOD_PKT");
    pkt.display();
  end
endmodule


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