Understanding of down casting

Hi Dave,

I watched one of your session on OOP for down casing. I tried very simple example, state below, but I am seeing error with VCS and Modelsim, complaining about Dynamic Cast Failure. I am unable to understand why it is not able to cast parent handle to child?

class A;

int a=1;

endclass

class B extends A;

int b=2;

endclass

class C extends B;

int c=3;

endclass

module test();

A a = new();
B b;
C c;

initial begin
// Down casting
$cast(c, a);
$display(“Print c.c %0d”, c.c);
end

endmodule

Error with VCS:
Error-[DCF] Dynamic cast failed
dave.sv, 27
Casting of source class type ‘A’ to destination class type ‘C’ failed due to
type mismatch.
Please ensure matching types for dynamic cast

Can you help me understand why it is unable to down cast?

In reply to Nimesh Patel:

What you show here is not down-casting. Down-casting means that you created an instance belonging to some derived-class, but for some reason, afterwards, you’ve stored it in a base-class reference. In that case you can down-cast it back to the derived-class. With UVM if you have a specific derived class of uvm_component, you would often pass it to functions that accept a uvm_component, i.e. the base-class, as parameter. Therefore, if you want to access the specific subtype fields, you’ll have to down-cast.

here’s your modified example running

In reply to avidan.efody:

Thanks, it helped me understand it.