I have an example,
class A;
int a=10;
function void disp();
$display(“a=%d”,a);
endfunction
endclass
class B extends class A;
int a=20;
endclass
program main();
A a;
B b;
b =new();
b.disp(); //diplays a=10
$display(“b.a=%d”,b.a); // displays a=20
endprogram
My questions are, now b has two a’s and a disp() function. How does simulator know which value of a to display when I call b.disp() ??
2nd : what is the OOP concept governing this situation and does this have a real time usage?
3rd question: How can I access a of base class with derived class handle in program block?
Call property references are not virtual; that means the class type of the reference variable determines which property is accessed at compile time, not the type of the class object at run time.
Every non-static class method has an implicit this argument that is inserted by the compiler. So your class A is effectively
class A;
int a=10;
endclass
function void A::disp(A this);
$display("a=%d",this.a);
endfunction
and the b.disp() call becomes
A::disp(b);
Since the type of the this argument is A, this.a will always refer to the property in A, regardless of the actual class object being a type extended from A.
Having a class property with the same name in the base and extended class is usually not a good idea.
If you had the code below, you would be able to access a of the base class.
a = b;
$display("a.a=%d",a.a); // displays a.a=10