Can someone help me to understand how class inheritance for variable declaration with initial value?
Specifically, for variable name, only define get_name() function, the extended class can get the updated name.
class A;
/*const */string name = "A";
virtual function string get_name();
return name;
endfunction // get_name
virtual function void print_it();
$display("name:%s",get_name());
endfunction // print_it
endclass
class B extends A;
/*const */string name = "B";
`ifdef SUB_METHOD
virtual function string get_name();
return name;
endfunction // get_name
`endif
endclass // B
module tb;
A a;
B b;
initial begin
a = new();
b = new();
a.print_it();
b.print_it();
end
endmodule
I think oyu are confusing overwriting the initial value with adding a new class variable. Your class B adds another variable called “name” that is only visible in the extended class. That is why you needed virtual method get_name in the extended class to access it. What you could do is overwrite name in the extended constructor.
class A;
string name = "A";
virtual function void print_it();
$display("name:%s",name);
endfunction
endclass
class B extends A;
function new;
name = "B";
endfunction
endclass
I like your idea by adding new() although it could be old, Dave.
If the variable - name is static type, then the problem comes. Both base & extended class will print out the updated value - B, which will break the pattern of class inheritance.
I came across this in UVM pkg specifically for type_name, which confuse me a lot.
class A;
static string name = "A";
virtual function void print_it();
$display("name:%s",name);
endfunction
endclass
class B extends A;
function new;
name = "B";
endfunction
endclass // B
module tb;
A a;
B b;
initial begin
a = new();
b = new();
a.print_it();
b.print_it();
end
endmodule
Note that type_name is never defined in the uvm_object base class, just the virtual method get_type_name() which returns “< undefined >” if your class is not registered with the factory.
Also note the UVM improperly uses
const static to declare
type_name when it should have used
localparam. A
const declaration is a write once variable, not a true constant like a parameter or localparam.
You are correct, type_name is not defined in uvm_object base class. If the extended relation is like this in UVM, user needs to consider overriding the get_type_name() in extend class B.
uvm_object ← A ← B #(type T=int) (parameterized class)
Although B is registered with factory, m_uvm_get_type_name_func** is missing in **uvm_object_param_utils_begin.
In order to get_type_name() to print out the actual type_name for B, user needs to add `m_uvm_get_type_name_func(T) to update the initial value on type_name as well as the method - get_type_name().