Trying to understand $cast and Factory. I made a simple example from reference code.
Reference code
class base;
int unsigned b;
endclass : base
class derived extends base;
int unsigned d;
endclass : derived
module top();
initial begin
base B;
derived D;
D = new();
D.b = 'hB;
D.d = 'hD;
B = D;
if ($cast(D, B)) begin
$display ("D.b:%0h", D.b);
$display ("D.d:%0h", D.d);
end
end
endmodule : top
From reference code, I get it the $cast() functionality which I can use a variable “b” from D.
So I made two example for understand casting under overriding.
- $cast() with override.
import uvm_pkg::*;
`include "uvm_macros.svh"
class agent_a extends uvm_agent;
`uvm_component_utils(agent_a)
int a=1;
function new(string name = "agent_a", uvm_component parent = null);
super.new(name, parent);
endfunction : new
endclass : agent_a
class agent_b extends agent_a;
`uvm_component_utils(agent_b)
int b=2;
function new(string name = "agent_b", uvm_component parent = null);
super.new(name, parent);
endfunction : new
endclass : agent_b
class agent_c extends agent_b;
`uvm_component_utils(agent_c)
int c=3;
function new(string name = "agent_c", uvm_component parent = null);
super.new(name, parent);
endfunction : new
endclass : agent_c
module test_module ();
initial begin
agent_a agent_a_h;
agent_b agent_b_h;
agent_c agent_c_h;
int cast1;
agent_a::type_id::set_type_override(agent_b::get_type());
factory.print();
agent_a_h = agent_a::type_id::create("agent_a_h", null);
agent_a_h = agent_c_h;
cast1 = $cast(agent_c_h, agent_a_h);
$display("casts =%01d, agent_c_h.a=%01d, agent_c_h.b=%01d ", cast1, agent_c_h.a, agent_c_h.b );
In “2. $cast() with override”, cast success. but I have faced that *E,TRNULLID: NULL pointer dereference. I expected that I can downcast by $cast(agent_c_h, agent_a_h); but why I got faced NULL pointer dereference error about agent_c_h?