SystemVerilog Reference

virtual Methods

A virtual method is chosen by the object, not by the handle. This is what makes overriding work.

Syntax

class Base;
  virtual function void show(); ... endfunction
endclass
class Child extends Base;
  function void show(); ... endfunction   // overrides
endclass

Rules

  • Through a base handle, a virtual method runs the version of the actual object.
  • A non-virtual method runs the version of the handle type.
  • Once a method is virtual, it is virtual in every child class.
  • The override must keep the same arguments and return type.
  • super.show() calls the parent version from inside the override.

Example

class Base;
  virtual function void show(); $display("virtual: Base"); endfunction
  function void plain();        $display("plain:   Base"); endfunction
endclass

class Child extends Base;
  function void show();  $display("virtual: Child"); endfunction
  function void plain(); $display("plain:   Child"); endfunction
endclass

module tb;
  initial begin
    Child c = new();
    Base  b = c;      // base handle, child object
    b.show();
    b.plain();
  end
endmodule
Output on Verilator 5.052
virtual: Child
plain:   Base

Run It in the Playground

Common Mistake

Forgetting virtual in the base class

class Base;
  function void show(); ... endfunction   // not virtual
endclass
// b.show() on a Child object still runs Base::show

Without virtual, the call is fixed by the handle type at compile time. The override is never reached through a base handle.

Fix: Declare the method virtual in the base class.

Learn It Properly

These lessons teach it step by step, with practice problems.

Standard

IEEE 1800-2023, 8.20.