What is the actual need of casting?

Here is an example of downcasting.

class a;
  logic x=1'bz;
endclass

class b extends a;
  bit x;
endclass

module tb;
  
  b b1=new;
  a a1;
  
  initial
    begin
      b1.x=1;
      a1=b1;
      $display(a1.x);
      $cast(b1,a1);
      $display(b1.x);
      $display(a1.x);
    end
endmodule

output:   z
          1
          z

Here, at first, I have created object b1 of the derived class and assigning its handle to the base class object handle and then after assigning a base class to handle a1 to the b1 again and this is called downcasting.

Not able to understand what is the need for downcasting.
In the above example, you can see that initially and after the casting b1 object is pointing to the same location.
So what does it changes?

In reply to Harin Maniyar:



class A;
  rand int a,b;
  virtual function void copy(A a_h);
    this.a = a_h.a;
    this.b = a_h.b;
  endfunction
endclass
 
class B extends A;
  rand int i,j;
  function void copy(A a_h);
     B b_h;
     $cast(b_h,a_h);
     super.copy(b_h);
     this.i = b_h.i;
     this.j = b_h.j;
  endfunction
endclass

A a1;
B b1,b2;
initial
  begin
  b1 = new();
  assert (b1.randomize);
  b2 = new();
  b2.copy(b1)// calling the copy function in child class

As shown in the above example consider a parent class in which a virtual method copy is defined.In child class the virtual copy method is overridden.

Within initial begin two objects for child class b1, b2 has been created . Now to copy the object b1 to b2 the copy method is called as shown above.

When the copy method inside the child class is called, b1 will be assigned to the argument of copy method i.e., a_h will point to child class object b1. Now inside the copy method we have the parent class handle a_h pointing to child object b1, but using a_h we can access the properties in child object.In order to access it we will declare another child class handle b_h & cast it with parent handle so that b_h will also point to the object b1 and now using b_h we can access the properties of object b1.

In reply to Harin Maniyar:

To explain the results your are seeing, when constructing a class B object, you get all the members of class B and class X. You have two x variables.

You may want to read this as well as the links it contains.

In reply to shanthi:

Thanks for explaining with an example I got your point about why we use $cast.

But, as per the function of copy you have written in the example we have to pass like


b1.copy(b2);

so it will copy object b2 into b1. But we haven’t initialized b2.

Instead of that, we can write that

b2.copy(b1);

Then it will copy the b1 object to b2. Am I write?
Once again thank you very much.

In reply to dave_59:

Thank you Dave for sharing.
Now I am much clear about the casting.

In reply to Harin Maniyar:

Yes Harin, you are right by oversight I have called b1.copy(b2) instead b2.copy(b1).