SystemVerilog OOP Mastery · All levels

Abstract Classes with `virtual class`: Exercises

Exercises for Abstract Classes with `virtual class`.

Practice exercises

Exercise 1

Create a `virtual class transaction_base` with fields `addr` and `data`, and a shared `print()` function. Then derive `apb_transaction` and instantiate only the derived class.

Solution

diagram
Declare `transaction_base` as `virtual class`, implement `print()`, then define `class apb_transaction extends transaction_base; ... endclass`. In test code, instantiate `apb_transaction t = new();` and call `t.print()`.

Exercise 2

Refactor a concrete checker class so that comparison policy becomes abstract while pass/fail logging remains shared.

Solution

diagram
Move logging counters and log/report utilities into a `virtual class checker_base` and declare `pure virtual function bit compare(...)`. Implement `compare` in each specialized checker class.

Related topics