SystemVerilog OOP Mastery · All levels
Classes and Objects: Exercises
Exercises for Classes and Objects.
Practice exercises
Exercise 1
Write a class item with rand fields kind and value. In an initial block, show that the handle is null before allocation, then allocate and randomize safely.
Solution
diagram
class item;
rand bit [1:0] kind;
rand bit [7:0] value;
endclass
module ex1;
initial begin
item it;
assert(it == null);
it = new();
assert(it.randomize());
end
endmoduleExercise 2
Create a function new_item() that allocates and randomizes an item with value in [10:20], and returns the handle.
Solution
diagram
function automatic item new_item();
item it = new();
assert(it.randomize() with { value inside {[10:20]}; });
return it;
endfunction