|  | 
|  |  | 
 |  
|  |  |  |  
|  |  | 
 |  
|  |  | Constructors |  
|  |  | SystemVerilog does not require the complex memory allocation and deallocation of C++. Construction of an object is straightforward; and garbage collection, as in Java, is implicit and automatic. There can be no memory leaks or other subtle behavior that is so often the bane of C++ programmers. |  
|  |  | 
 |  
|  |  | 
 Constructors like in C++ is done with reserve word new. Constructors should be function and not a task. Constructors does not return values. Constructors like any other function take input parameters. There can be only one constrcutor per class. |  
|  |  | 
 |  
|  |  |  |  
|  |  | 
 |  
|  |  | Example - Constructors |  
|  |  | 
 |  
|  |  | 
  1 `define PRINT task print (); \
  2           begin \
  3             $write("Size is %0d\n",this.size); \
  4           end \
  5        endtask
  6 
  7 program class_t;
  8   // Class with constructor, with no parameter
  9   class A;
 10      integer size;
 11      // Constructor
 12      function new ();
 13        begin
 14          this.size = 0;
 15        end 
 16      endfunction
 17      // Task in class (object method)
 18      `PRINT
 19    endclass
 20   // Class with constructor, with parameter
 21   class B;
 22      integer size;
 23      // Constructor
 24      function new (integer size);
 25        begin
 26          this.size = size;
 27        end 
 28      endfunction
 29      // Task in class (object method)
 30      `PRINT
 31    endclass
 32 
 33    // Class without constructor
 34    class C;
 35      integer size;
 36      task set_size(integer size);
 37        begin
 38          this.size = size;
 39        end
 40      endtask
 41      // Task in class (object method)
 42      `PRINT
 43    endclass
 44      
 45    A a;
 46    B b;
 47    C c;
 48 
 49    initial begin
 50      a = new();
 51      b = new(5);
 52      c = new();
 53      a.print();
 54      b.print();
 55      c.print();
 56    end
 57 
 58 endprogram
You could download file class_con.sv here |  
|  |  | 
 |  
|  |  | Simulation - Constructors |  
|  |  | 
 |  
|  |  |  Size is 0
 Size is 5
 Size is x
 |  
|  |  | 
 |  
|  |  | 
 |  
|  |  | 
 |  
|  |  |  |  
|  |  | 
 |  |  | 
|  
 |  
 |  
 | 
| 
 | 
|    |  
| Copyright © 1998-2025 |  
| Deepak Kumar Tala - All rights reserved |  
| Do you have any Comment? mail me at:deepak@asic-world.com
 |  |