Queue of objects

class cls; 
rand integer Var; 
endclass 

class q_cls; 
rand cls obj[$]; 
rand bit [2:0] length; 

function void pre_randomize(); 
length = $urandom % 20 ; // Compute the length of queue. 
obj = {} ; // Delet all the elements in the queue or .delet can be used 
repeat(length) 
begin 
cls obj_loc; 
obj_loc = new(); // Creat new object. 
obj.push_back(obj_loc) ; // insert it into queue. 
end 
endfunction 
endclass 

program q_obj_p_93; 
q_cls obj1= new(); 

initial 
begin 
  if(obj1.randomize()) 
begin 
$display( "Randomization done"); 
  $write( " Length of q : %0d :::",obj1.length); 
  for(int i ;i< obj1.length;i++) 
begin 
cls obj_temp; 
  obj_temp=new();
obj_temp = obj1.obj.pop_front(); 
  $write(" : %0d : ",obj_temp.Var); 
end 
end 
else 
$display( "Randomization failed"); 
end 
endprogram


The object at dereference depth 0 is being used before it was
constructed/allocated.
Please make sure that the object is allocated before using it.

#0 in unnamed$$_5 at testbench.sv:37
#1 in q_obj_p_93

please can anyone rectify the above code

In reply to suresh M:

Hi Suresh,

Problem is with “length” variable.

First time it is randomized in function “pre_randomize” .
Suppose length=5 ; so it will create queue of 5 objects.

Second time it gets randomized when you call “obj1.randomize()”
Suppose this time it is length=9; so code is trying to iterate 9 times while queue has only 5 objects.

Solution:
1).Use post_randomize method instead of using pre_randomize method.
2).Change code to retain value of length obtained during ‘pre_randomize’ method and use this value inside program block ‘for_loop’.

Have a nice day !!

In reply to DigvijayS:

Other solution would be to not declare length variable as rand. What is the point of declaring variable rand if you are going to use $urandom.