Wednesday 27 May 2015

How $cast works

$cast is a system task which is used to assign source type to destination type.

Dynamic cast ($cast) checks whether casting is possible or not during run-time and gives run-time error if casting is not possible, unlike in case of static casting it gives compile time error if casting is not possible. If casting is failed then source type would remain as it is.
  • $cast (destination type, source type) expression returns 1 if source type can be cast into destination type.
  • $cast (destination type, source type) expression returns 0 if source type can not be cast into destination type.
Examples:

1.       Basic Example
int a = 10;
int b = 20;
$cast(a,b);                                  // Dynamic cast
a = b;                                            // Static cast

2.       Object casting
class parent_c;
   virtual task display_name();
     $display(“Class Parent”);
   endtask
endclass

class child1_c extends parent_c;
   virtual task display_name();
      $display(“Class child1”);
   endtask
endclass

class child2_c extends parent_c;
   virtual task display_name();
      $display(“Class child2”);
   endtask
endclass

A)  Casting of child class to parent class can be possible because child class and parent class have same data type. Example is showed below.
program main;
   initial begin
     parent_c p;
     child1_c c1;
     child2_c c2;
    
     c1 = new();
     $cast(p, c1);
     p.display_name();
     c2 = new();
     $cast(p, c2);
     p.display_name();
endprogram

Sim Results:
Class child1
Class child2

B)   Casting of child classes which exist in separate class hierarchy cannot be possible because they are of different data types. Example is showed below.
program main;
   initial begin
     parent_c p;
     child1_c c1;
     child2_c c2;
    
     c1 = new();
     c2 = new();
     $cast(c1,c2);
     c1.display_name();
     $cast(c2,c1);
     c2.display_name();
endprogram

Sim Results:
*E-Dynamic cast failed
*E-Dynamic cast failed

C)   Casting of parent class to child class cannot be possible because they are of different data types. Example is showed below.
program main;
   initial begin
     parent_c p;
     child1_c c1;
     child2_c c2;
    
     c1 = new();
     c2 = new();
     $cast(c1, p);
     c1.display_name();
     $cast(c2, p);
     c2.display_name();
   end
endprogram

Sim Results:
*E-Dynamic cast failed
*E-Dynamic cast failed

No comments: