System Verilog LRM states the following points.
- It is always legal to assign a subclass variable to a variable of a class higher in the inheritance tree.
- It is never legal to directly assign a superclass variable to a variable of one of its subclasses.
- However,
it is legal to assign a superclass handle to a subclass variable if the superclass handle refers to an object of the given subclass
I have given examples for above statements.
Example 1:
class parent;
int i = 10;
endclass
class subclass extends parent;
int j = 20;
function new();
i = j;
$display(“I is %d J is %d”,i,j);
endfunction
endclass
program main;
initial
begin
subclass s;
s = new();
end
endprogram
output:
I is 20 J is 20
Example 2:
class parent;
int i = 10;
endclass
class subclass extends parent;
int j = 20;
function new();
j = i;
$display(“I is %d J is %d”,i,j);
endfunction
endclass
program main;
initial
begin
subclass s;
s = new();
end
endprogram
output:
I is 10 J is 10
Here I have query, as per 2nd statement in LRm, this example should not work.
Can any body explain me about this.
bdreku
2
In reply to umarfarooq:
Here, your example and the LRM statements are two different things.
Regarding your example,
Here, you are accessing a member of super class in to subclass, which is legal.
Regarding LRM statements,
- It is always legal to assign a subclass variable to a variable of a class higher in the inheritance tree.
i.e. you can always assign a handle of subclass to a super class handle.
parent p;
subclass s=new();
p=s; // it is valid
- It is never legal to directly assign a superclass variable to a variable of one of its subclasses.
i.e. you can not assign a handle of superclass to a subclass handle directly.
parent p=new();
subclass s;
s=p; // it will give an error
- However,
it is legal to assign a superclass handle to a subclass variable if the superclass handle refers to an object of the given subclass
i.e. there is a way to assign a superclass handle to a subclass handle if the superclass handle refers to a subclass object.
parent p;
subclass s,s2;
s=new();
p=s;
$cast(s2,p); // it is valid as the superclass handle refers to an object of the given subclass
Hi Umarfarooq,
Please refer to this below link.
www.testbench.in/CL_13_CASTING.html