Reputation: 51
I'm trying to studying the case by referring https://verificationacademy.com/courses/systemverilog-oop-for-uvm-verification
To understand $cast
, I've implemented as the below.
class A;
int v=1;
endclass
class F extends A;
int w=2;
endclass
class B extends A;
int x=3;
endclass
class G extends B;
int y=4;
endclass
class C extends B;
int z=5;
endclass
module test;
initial begin
A a_h = new();
B b_h;
G g_h;
C c_h;
F f_h;
$display(a_h.v);
if ( $cast(c_h, a_h) )
$display(c_h.z);
else if ( $cast(g_h, a_h) )
$display(g_h.y);
end
endmodule
But I've got just only
'1'
I think the below code doesn't work.
if ( $cast(c_h, a_h) )
$display(c_h.z);
else if ( $cast(g_h, a_h) )
$display(g_h.y);
Why does it have a Hierarchical name component lookup failed error?
If I want to cast G to A class then what am I supposed to do?
I've got error message when I implemented like the below
module test;
B b_h = new();
G g_h = new();
C c_h = new();
F f_h = new();
A a_h = new();
initial begin
$cast(c_h, a_h);
$display(c_h.z);
$display(b_h.x);
$display(a_h.v);
The error messages
$cast(c_h, a_h);
|
ncsim: *E,BCLCST (./test1.sv,33|5): Invalid cast: a value with the class datatype '$unit_0x118af7fb::A' cannot be assigned to a class variable with the datatype '$unit_0x118af7fb::C'.
5
3
1
As you can see, I've got 5, 3, 1 values but also Error message. Would you please let me know why I get this error message?
Upvotes: 0
Views: 7189
Reputation: 12384
In order to do this cast, you have to allocate the derived
class first, then use it as the base
class and only then you can cast, as in the following example.
class A;
int a = 1;
endclass
class B extends A;
int b = 2;
endclass
module C;
B b_h = new(); // << allocate the derived class
B bb_h;
A ba_h;
initial begin
ba_h = b_h; // << assign derived class to the base
if ($cast(bb_h, ba_h)) // << now you can cast base to another variable of class B (or to one of its bases).
$display(bb_h.b);
end
endmodule
Upvotes: 0