SystemVerilog OOP Mastery · All levels
Encapsulation with local and protected: Exercises
Exercises for Encapsulation with local and protected.
Practice exercises
Exercise 1
Design class credit_pool where available_credits is local and can only change via consume() and refill(). Include range checks.
Solution
diagram
class credit_pool;
local int unsigned available_credits;
function new(int unsigned init_credits = 8);
available_credits = init_credits;
endfunction
function void consume(int unsigned n);
if (n > available_credits) $fatal(1, "insufficient credits");
available_credits -= n;
endfunction
function void refill(int unsigned n);
available_credits += n;
endfunction
endclassExercise 2
Create a base class with protected rand addr and a child class that constrains addr alignment without exposing addr publicly.
Solution
diagram
class base_item;
protected rand bit [31:0] addr;
function bit [31:0] get_addr();
return addr;
endfunction
endclass
class aligned_item extends base_item;
constraint c_align { addr[1:0] == 2'b00; }
endclass