Accessing Properties of Derived class with the help of Base class

Here my code;
Is this is possible in a different way?


class A;
int i,j;
endclass

class B extends A;
int k;
endclass

class C;
A a1;
endclass

class D extends C;
B b1;
endclass

module test;
initial
begin
D d1;
d1=new;
d1.b1=new;
d1.a1=d1.b1;
$display(d1.a1.i);//possible
$display(d1.a1.k);//trying to access derived class properties but error (k is not a member of class A)
end
endmodule

In reply to Sureshkumar krishnasamy:

You can make use of getter method here. Use virtual method(e.g. get_properties(), as accessor) in both class A and B which returns its properties.

class A;
  int i,j;

  virtual function void get_properties();
    $display(i, j);
  endfunction

endclass

class B extends A;
  int k;

  function void get_properties();
    $display(k);
  endfunction

endclass

So, after this statement, ‘d1.a1=d1.b1’ When you call ‘d1.a1.get_properties()’, it’ll return properties of the “object type” pointed by the handle ‘a1’.

Hi,

Without using any function i need to access properties of class B with the help of class A handle.

In reply to Sureshkumar krishnasamy:

Hi,
Without using any function i need to access properties of class B with the help of class A handle.

It is not possible to access derived class properties by the parent handle without using polymorphism(virtual task/function) concept!

In reply to Sureshkumar krishnasamy:
You need to understand the difference between class types, class objects, class variables, and class handles. You can only access class properties that are defined by the type of the variable that stores a handle to an object.

In your example,
a1
is a variable of an
A
type, and can only access properties
i
and
j
. You then store a handle to an object whose type
B
extends from
A
into the
a1
variable, and you can no longer access property
k
from
a1
.

If you need to access property
k
, you’ve got to know that you are dealing with a type
B
object and access from a type
B
variable like
b1
, or you can use
$cast()
to move the handle stored in
a1
to another variable of type
B
.

You may want to review my SystemVerilog OOP course on the Verification Academy.