Base and Derived Class Randomization

class b;
  
  rand int a;
  rand int b;
endclass

class d extends b;
  
  constraint c3 {a == 35;}
  constraint c4 {b == 20;}
  
endclass 

module top;
  
  initial begin
    b b1;
    d d1;
    b1 = new();
    d1 = new();   
    b1 = d1;
    d1.randomize();
    $display("%d %d",b1.a,b1.b);
    $display("%d %d",d1.a,d1.b);   
    
  end 
  
endmodule 

The output of the above code:

35 20
35 20

i.e both base and derived class are referring to the same copies of a and b.

My doubt is why do b.a and b.b prints the value of the derived class?

In reply to prasham98:

The base class handle b1 is pointing to derived class object d1, so b1.a & b1.b prints the values of child class object which are inherited from base class.

In reply to shanthi:

From my understanding of inheritance, the derived class can access members of the base class but vice versa isn’t true.

In reply to prasham98:

When executing the statement
b1 = d1;
, you are copying the handle to the derived class object stored in the class variable d1 to the class variable b1. The handle to the base class object that was in b1 is lost, and now both b1 and d1 reference the same derived class object.

When you print d1.a and d1.a, you are printing the same class member.

In reply to dave_59:

In reply to prasham98:
When executing the statement
b1 = d1;
, you are copying the handle to the derived class object stored in the class variable d1 to the class variable b1. The handle to the base class object that was in b1 is lost, and now both b1 and d1 reference the same derived class object.
When you print d1.a and d1.a, you are printing the same class member.

Hi Dave,

With following logic

b1 = d1; // now b1 and d1 are pointing to d1

Now if just add variable c to derived class

int c = 10;

And try to print c through b1, I get error “Could not find member ‘c’ in class ‘b’”

In reply to UVM_SV_101:

The error is correct. This is one of the fundamental concepts of OOP. Please see one of the many courses on SystemVerilog OOP.

http://go.mentor.com/SV-OOP