SystemVerilog OOP Mastery · All levels
Encapsulation with local and protected: Code Examples
Code Examples for Encapsulation with local and protected.
Code examples
local and protected member declarations
systemverilog
class base_txn;
local int unsigned txn_id;
protected rand bit [31:0] addr;
function new(int unsigned txn_id = 0);
this.txn_id = txn_id;
endfunction
function void set_addr(bit [31:0] a);
addr = a;
endfunction
function bit [31:0] get_addr();
return addr;
endfunction
endclassSeeds the core pattern: local hides strict internals; protected allows controlled inheritance-level visibility.
Derived class can access protected but not local
systemverilog
class base_txn;
local int unsigned txn_id;
protected bit [31:0] addr;
endclass
class ext_txn extends base_txn;
function void tweak();
addr = 32'hABCD_0001; // legal: protected in base
// txn_id = 5; // illegal: local in base
endfunction
endclassClarifies the visibility boundary between inheritance users and outside users.
Validation through methods instead of public fields
systemverilog
class burst_cfg;
local int unsigned burst_len;
function void set_burst_len(int unsigned n);
if (n inside {[1:256]}) burst_len = n;
else $fatal(1, "burst_len out of range");
endfunction
function int unsigned get_burst_len();
return burst_len;
endfunction
endclassShows encapsulation as an invariant-preserving API: no external direct write can bypass checks.