SourceSV Verification Directory

Dynamic Cast

Casting refers to conversion of a variable to one data type to another data type. SystemVerilog provides two types of casting,

  1. Static Casting
  2. Dynamic Casting

Dynamic Casting

Dynamic casting in SystemVerilog allows you to safely convert a handle of one class type to another class type at runtime, ensuring the cast is valid and the object is of the target type. The dynamic cast, $cast, allows you to check for out-of-bounds values. Use dynamic cast when converting from a type with a large number of values than the destination, such as int to an enumerated variables.

Syntax

$cast (target_handle, source_handle);
  • target_handle: is the handle to which to convert.
  • source_handle: the handle from which to convert from.

Example Code

Dynamic casting is particularly useful in the context of Polymorphism when a parent class handle needs to be assigned to a child class handle.

// Parent class
class parent_class;
   // class properties or variables
  int a, b, s;


   // task method
  task func ( );
    s = a + b;
    disp();
  endtask

  function void disp( );
    $display("Parent Class => a = %0d , b = %0d, sum s = %0d", a, b, s);
  endfunction


endclass

// Child Class
class child_class extends parent_class;
  // class properties or variables
  int m;

  // task method
  task func ( );
    m = a * b;
    disp();
  endtask

  function void disp( );
    $display("Child Class  => a = %0d , b = %0d, mul m = %0d", a, b, m);
  endfunction

endclass

module test;

  parent_class pr_obj;          // declare a handle for parent class
  child_class cl_obj;           // declare a handle for child class

  child_class cl_obj_2;         // declare another handle for child class

   initial begin
     cl_obj = new( );           // construct an object

     pr_obj = cl_obj;
     $cast(cl_obj_2, pr_obj);   // DYNAMIC CASTING
                                // parent class assigned to child class

     pr_obj.a = 20;
     cl_obj.b = 15;


     $display("------------ Dynamic Casting ------------");
     cl_obj_2.func();

   end

endmodule

Execute the code in EDA Playground