Guilty
Guilty

Reputation: 492

SystemVerilog: Aggregate class with array of class objects

I want to have a SystemVerilog class which contains an array of another class, like below:

class AggregateClass;
  integer x;
  OtherClass[x] otherClassArray;
  extern function new(int x, logic in);
endclass: AggregateClass

class OtherClass;
  // ...
  extern function new(logic in);
  // ...
endclass: OtherClass
  1. How do I define an array of classes in SystemVerilog?
  2. How can I have the number of class objects in said class array be set by the constructor?

Upvotes: 1

Views: 643

Answers (1)

Serge
Serge

Reputation: 12384

When declaring a static array, you need a constant to declare its size; so, a variable cannot be used there. However, in SystemVerilog you can use dynamic arrays as follows:

class B;
  int val;
  function new(int v);
    val = v;
  endfunction
  function void print;
    $display("%0d", val);
  endfunction
endclass

class A;
  int x;
  B b[int]; // << declaration of a dynamic array
  
  function new(int n);
    x = n;
    for (int i = 0; i < n; i++)
      b[i] = new(i); // <<< construction of dynamic array elements of class B.
  endfunction
  
  function void print;
    $display("size: %0d", b.size);
    for (int i = 0; i < x; i++)
      b[i].print;
  endfunction
  
endclass
  
module top;
  initial begin
    A a = new(4);
    a.print();
  end
endmodule

Upvotes: 1

Related Questions