In reply to kbkdec15:
Hi kbkdec15,
I hope by this time you must have found the answer for this.
We take the advantage of inheritence and polymorphysm of SV classes here. Upcasting is where we assign the derived class’s handle to base class. The advantage is obvious: reusability.
class base;
int a = 5;
endclass
class child extends base;
int b = 6;
endclass
module top;
initial begin
base base_h;
child child_h;
child_h = new();
$cast(base_h, child_h); // same as: base_h = child_h;
$display(child.a); // a is base's property
end
endmodule
Now downcasting is opposite of the above; assigning the base class handle to child class handle. But this will not work until the base class handle already refers to child class handle. When an array of base class is present, where it is filled with different child class handles, this downcasting comes handy. Check the following code (copied from casting - Does SystemVerilog support downcasting? - Stack Overflow):
class animal;
function void eat();
endfunction
endclass
class dog extends animal;
function void bark();
$display("woof");
endfunction
endclass
class cat extends animal;
function void meow();
$display("meow");
endfunction
endclass
module test;
initial begin
dog a_dog = new();
cat a_cat = new();
animal animals[$];
animals.push_back(a_dog);
animals.push_back(a_cat);
foreach (animals[i]) begin
dog another_dog;
animals[i].eat();
if ($cast(another_dog, animals[i])) begin
$display("Found a dog!");
another_dog.bark();
end
end
end
endmodule
Hope that helps.
-mpattaje