SystemVerilog OOP Mastery · All levels

Handles, new(), and Construction Patterns: Exercises

Exercises for Handles, new(), and Construction Patterns.

Practice exercises

Exercise 1

Implement class frame with fields id and crc. Add clone() and prove that editing clone does not change original.

Solution

diagram
class frame;
  int unsigned id;
  bit [31:0] crc;
  function frame clone();
    frame c = new();
    c.id = this.id;
    c.crc = this.crc;
    return c;
  endfunction
endclass

module ex2;
  initial begin
    frame a = new();
    frame b;
    a.id = 9; a.crc = 32'h1111_2222;
    b = a.clone();
    b.id = 99;
    $display("a.id=%0d b.id=%0d", a.id, b.id);
  end
endmodule

Exercise 2

Create a class agent_cfg with optional timeout_cfg handle and a get_timeout() method that is safe even when timeout_cfg is not preallocated.

Solution

diagram
class timeout_cfg;
  int unsigned cycles;
  function new(int unsigned cycles = 1000);
    this.cycles = cycles;
  endfunction
endclass

class agent_cfg;
  timeout_cfg tcfg;
  function int unsigned get_timeout();
    if (tcfg == null) tcfg = new();
    return tcfg.cycles;
  endfunction
endclass

Related topics