Memory allocation when classes are assigned to each other

Hi ,

I’m assigning a derived class to a base class as shown in the below example . But , when I’m displaying the value of variable A using the base class handle , I’m seeing that A gets the value in the base class (3) . When classes are assigned to each other , they share a common memory and it isn’t overridden . So , is it right for the value of A to be printed as 3 or should it be 20 ?

class base;

  int A  =3;

  virtual function void cpy( );
     A =50 ;
     $display("not supposed to be here");
  endfunction

endclass

class derived extends base ;

     int A =20 ;

     function void cpy();
       A =100;
       $display("derived call here");
     endfunction

endclass

module top();
  initial begin
    derived  derived_class2 ;
    base     base_class2;

    derived_class2 =new();

    base_class2 = derived_class2 ; 

    derived_class2.cpy();
    base_class2.cpy();
 
    $display("A in derived class2 through cpy =%0d" ,derived_class2.A);
    $display("A in base  class2 through cpy =%0d" ,base_class2.A);

  end
endmodule

OUTPUTS :

derived call here
derived call here
A in derived class2 through cpy =100
A in base  class2 through cpy =3

In reply to ra_su:
Please use code tags making your code easier to read. I have added them for you.

When extending a class, class properties get inherited, not overriden. The derived class contains 2 properties, base::A and derived::A. You constructed a single derived class object, and its handle got stored in the class variables base_class2 and derived_class2.

Since you declared cpy as a virtual method, both derived_class2.cpy() and base_class2.cpy() call the same method, derived::cpy(). And both calls set the same variable, derived::A to 100.

base:cpy() never gets called, so base::A remains 3. base_class2.A refers to base::A. A class variable only can reference what is defined by it’s class type, regardless of what extended object handle might be stored in it.