Advanced OOP Questions

01

Can a Constructor be Virtual? What about Destructor?

+

Constructors (`new`) cannot be virtual in SystemVerilog because the object type must be known at creation time to allocate memory.

However, Factory Patterns (like in UVM) simulate virtual constructors using `create()`, which allows overriding the object type dynamically.

There is no explicit "Destructor" in SV (automatic garbage collection handles this), so the concept of a virtual destructor doesn't apply like in C++.

02

Explain `$cast`: Dynamic Casting

+

`$cast(destination, source)` attempts to cast a handle from `source` to `destination` at runtime.

  • Downcasting (Base -> Derived): Requires `$cast`. Checks if the Base handle actually points to a Derived object. Returns 0 if failed, 1 if success.
  • Upcasting (Derived -> Base): Always safe, done implicitly.
Base b = new();
Derived d;
if (!$cast(d, b)) $display("Cast Failed!"); // Fails: 'b' is not 'Derived'
03

Difference between Abstract Class and Interface Class?

+
  • Abstract Class (`virtual class`): Can contain implementation (data members, defined methods) AND pure virtual methods. Cannot be instantiated directly. Single inheritance (`extends`).
  • Interface Class (`interface class`): Contains ONLY pure virtual methods and parameters (no data, no implementation). A class can `implement` multiple interface classes (Simulates multiple inheritance).