SystemVerilog OOP Mastery · All levels

Polymorphism and Dispatch Semantics: Code Examples

Code Examples for Polymorphism and Dispatch Semantics.

Code examples

One base-handle queue driving multiple derived classes

systemverilog
virtual class driver_base;
  pure virtual task drive();
endclass

class axi_driver extends driver_base;
  virtual task drive();
    $display("AXI drive");
  endtask
endclass

class apb_driver extends driver_base;
  virtual task drive();
    $display("APB drive");
  endtask
endclass

module tb;
  driver_base drivers[$];

  initial begin
    drivers.push_back(new axi_driver());
    drivers.push_back(new apb_driver());
    foreach (drivers[i]) drivers[i].drive();
  end
endmodule

The queue stores base handles, but each drive call dispatches to the actual derived object because drive is virtual.

Safe downcast using $cast before derived access

systemverilog
class txn_base;
  virtual function string kind();
    return "base";
  endfunction
endclass

class read_txn extends txn_base;
  rand bit [31:0] addr;
  virtual function string kind();
    return "read";
  endfunction
endclass

module tb;
  task automatic inspect(txn_base t);
    read_txn r;
    if ($cast(r, t)) begin
      $display("READ addr=%08h", r.addr);
    end else begin
      $display("kind=%s", t.kind());
    end
  endtask

  initial begin
    txn_base t = new read_txn();
    inspect(t);
  end
endmodule

Use $cast for runtime-checked downcast. This is the safe way to access derived-only fields while still accepting generic base handles.

Related topics