Classes, Inheritance, and Polymorphism
Model test transactions, understand handles, and extend behavior without copying an entire environment.
A test object, not a circuit
A class describes data and the methods that operate on it. It is dynamically allocated and normally not synthesizable. In a testbench, a class often represents a transaction, generator, or checking component.
class bus_transaction;
rand bit write;
rand bit [15:0] address;
rand bit [31:0] data;
function new(bit [15:0] address = '0);
this.address = address;
endfunction
virtual function void display();
$display("write=%0b address=%04h data=%08h",
write, address, data);
endfunction
endclassThe class declaration defines a type. The object exists only after new:
bus_transaction tr;
tr = new(16'h0100);
tr.display();tr is a handle, similar to a reference. Assigning tr to another handle does not copy the object. Both handles then refer to the same instance.
Inherit for a real specialization
A derived class receives the fields and methods of its base class.
class error_transaction extends bus_transaction;
bit inject_parity_error;
function new();
super.new();
inject_parity_error = 1'b1;
endfunction
virtual function void display();
super.display();
$display("inject_parity_error=%0b", inject_parity_error);
endfunction
endclassInheritance fits when the derived class truly remains a form of the base class. Avoid a deep hierarchy created only to share a few lines of code.
Polymorphism and virtual methods
A base-type handle can refer to a derived object:
bus_transaction base_handle;
error_transaction error_tr = new();
base_handle = error_tr;
base_handle.display();Because display is virtual, the call uses the error_transaction implementation. A generator or driver can work with the base type while accepting specialized variants.
Without virtual, method selection would follow the handle type instead of the actual object type.
Copying and lifetime
A handle assignment is a shallow copy of the reference. To obtain two independent objects, create the second object and copy fields, usually through a dedicated method.
Objects are reclaimed when no handle refers to them. Circular references and unnecessarily retained handles make long-running environments harder to debug.
Key points
- A class variable is a handle and
newcreates the object. - Copying a handle does not duplicate the object.
- Inheritance represents a real specialization of the base type.
- A
virtualmethod lets the actual object type select the implementation. - Classes belong in testbenches, not ordinary synthesizable RTL.
📝 Test your knowledge - Chapter quiz