Unexpected Behavior of Code


class A;

int a;

function void DISP();
$display("HI IN A with a==%0d",this.a);
endfunction

endclass

class B extends A;

int b;

function void DISP();
$display("HI IN B with a==%0d",this.a);
endfunction

endclass

module TP;

A a1;

B b1;


initial begin
b1 = new();
b1.a = 10;
a1 = b1;
a1.DISP(); 
$display("a1.a==%0d b1 == %p",a1.a,b1); // O/P :: a1.a==10 b1 == '{super:'{a:10}, b:0}
end

endmodule


I have a few Queries
[1] Why is a1.a is 10 ? Properties ain’t Virtual so how Does a1.a Point to Property a within
Class B
[2] Since DISP() isn’t virtual I get " HI IN A with a==10" . Shouldn’t it Give a Fatal Error Since we access Property without creating it ??

In reply to Etrx91:

Because you have assigned handle of class B to handle of class A. Now, both (a1 and b1) will point same memory.

here as you have allocated memory for b1, and then you are assigning child class handle to parent class handle. so both are pointing to the same memory.then you are trying to access the property of parent class but that was override by the child class property. that’s why the value of a is 10. but incase of methods we have to use virtual otherwise it will not be override by the child class (concept of polymorphism) and it will point to the parent class method only. that is happening here…

In reply to Mohan Shyam:

Since they point to same Memory Shouldn’t a.b Work in $display ?
eg :: $display(a1.b);

In reply to Etrx91:

When you extend a class, you inherit al the properties in the base class. There are not two separate objects. (This is why I don’t like using parent/child when talking about inheritance. The type of the class variable that you use as a reference determine what you access, not the type of the object whose handle is stored in the class variable. a1 only lets you reference properties defined in class A even though the properties in class B are part of the object.

Please see my course on SystemVerilog OOP. All of this is explained in the second session.