As we know that in SystemVerilog Class Properties do not get created until the Object gets constructed. But there is an exception to that. When we add a “static” modifier to a Property that Property becomes a Static variable and it is Global to the Class type. It is created as soon as we create the type and it’s available during the entire simulation. We access Static Class Properties, not by Handle but using the Scope resolution operator i.e. “::”. One more important thing to note about Static Properties is that they’re visible simultaneously to all the instances of the Class.
Let’s see below an example related to Static Properties:
class Packet; int id; static int pkt_id; endclass: Packet program main; Packet dynapkt ; initial begin dynapkt = new; foreach (dynapkt[i]) begin dynapkt[i] = new(); dynapkt[i].id = Packet::pkt_id++; $display("dynapkt[%0d].id = %0d", i, dynapkt[i].id); end for (int i = 0; i<dynapkt.size(); i++) begin $display("dynapkt[%0d].pkt_id = %0d", i, dynapkt[i].pkt_id); end end endprogram
Here is Class “Packet” is having two Properties. One of them i.e. “id” is an integer and another one i.e. “pkt_id” is a Static Property. A dynamic array of type Packet Class is declared and later five Objects are constructed. After that using the Scope resolution operator (::) id value is assigned to each Object. In the end, the “for” loop shows that the Static Property pkt_id is reflected in all the instances of the Packet Class.
In SystemVerilog, we can create a Static Method inside a Class that can only read & write Static variables, even before any Object of that Class is constructed. Non-Static variables are not allowed inside the Static Methods.
Let’s understand through the below example:
class Packet; int id; static int pkt_id; static function int PKT_ID; return PKT_ID++; endfunction: PKT_ID endclass program main; Packet dynapkt ; initial begin dynapkt = new; foreach (dynapkt[i]) begin dynapkt[i] = new(); dynapkt[i].id = Packet::PKT_ID; $display("dynapkt[%0d].id = %0d", i, dynapkt[i].id); end end endprogram
In the above example, we defined a Static function i.e. PKT_ID which returns the incremented value of a Static variable called pkt_id. And PKT_ID is used with the scope resolution operator to assigned the incremented values to the non-static integer variable i.e. id of the created Objects.