SystemVerilog OOP Mastery · All levels
clone() and copy() Methods: Code Examples
Code Examples for clone() and copy() Methods.
Code examples
Base class copy/clone contract
systemverilog
class txn_base;
rand bit [31:0] addr;
rand bit write;
virtual function void copy(txn_base rhs);
addr = rhs.addr;
write = rhs.write;
endfunction
virtual function txn_base clone();
txn_base c = new;
c.copy(this);
return c;
endfunction
endclasscopy moves state between already-allocated objects. clone guarantees a fresh object by allocating first and then reusing copy logic.
Derived override with super.copy and $cast
systemverilog
class write_txn extends txn_base;
rand bit [63:0] data;
virtual function void copy(txn_base rhs);
write_txn wrhs;
super.copy(rhs);
if (!$cast(wrhs, rhs)) begin
return;
end
data = wrhs.data;
endfunction
virtual function txn_base clone();
write_txn c = new;
c.copy(this);
return c;
endfunction
endclassThe super.copy call guarantees base fields are handled once. The $cast protects derived field copy from type mismatch when the API accepts base handles.
Scoreboard stores clones for stable history
systemverilog
class scoreboard;
txn_base exp_q[$];
function void push_expected(txn_base tr);
exp_q.push_back(tr.clone());
endfunction
endclassQueueing clones avoids later mutation of producer-owned handles and keeps expected history immutable from the scoreboard point of view.