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?
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.