The size constraint for dynamic array of primitive data type works fine.
when changing from primitive to class object, it does not work, because this will incur null pointer error.
class my_cons_1;
rand my_class my_q1[]; // my_class is a custom class with rand variables here
rand int my_size;
constraint my_con{
my_q1.size() == my_size; // doesn't work here because no object constructed.
//other constraint over my_q1 elements
}
endclass
my question is:
Q1:why doesn’t constraint solver call class’s default constructor when solving the constraint in this case?
Q2:are there any other ways to achieve this? I know I could randomize my_size outside first and passed in as an normal int, and construct my object array inside pre_randomize function, but I’d like to do the randomization all at once if possible.
Let me address your second question first. The recommended practice is constructing a dynamic array with a maximum size first and constructing each element first. Then let randomization prune the array to the desired size. This has the benefit of preserving random stability since the number of constructed objects affects the random seeding. If calling randomize() causes the construction of a random number of objects, then a modification of constraints could lead to a disturbance in randstate for randomization statements that occur after it.
That should also cover most of your first question, but other reasons include the difficulty in passing arguments to the constructors during randomization.
class A;
rand int x;
constraint my_con{
x inside {1,2,3,4,5};
}
endclass
module tb_top;
class B#(parameter int MAX = 32);
rand A my_q1[];
rand int my_size;
function new();
endfunction
function void pre_randomize(); // pre-construct dynamic array of obj to MAX size
my_q1 = new[MAX];
foreach(my_q1[i])
my_q1[i] = new();
endfunction
constraint my_con{
my_q1.size() == my_size; // use size to prune dynamic array to desired size.
foreach(my_q1[i])
my_q1[i].x == 2;
}
endclass
initial begin
B b;
b = new();
b.randomize() with{my_size == 3;};
b.randomize() with{my_size == 4;};
foreach(b.my_q1[i])
$display("i: %0d, x %0d",i,b.my_q1[i].x);
end
endmodule