Classes contains properties and methods. Methods perform operations on the class properties. Class name will be used as type to declare the variable or handle for the class.
Instance for the class is created with the constructor which is new method. When you call the new method memory is allocated to class and its properties. If you dont declare the new method for the class it will be implicitly declared.
An explicit constructor can be created to initialize the properties of the class or for calling up some methods etc. Like if you see in the below example we have created a new method for the class mem_transfer which takes a argument addr_in and initilize the class property addr and data property is initialized to 0.
The properties which are not initialized will take the default values for that datatype. System verilog performs the automatic memory management for you unlike C++ to avoid the memory leaks. System verilog deletes the objects which is no more accessed in the code. Ofcourse you can not play like C++ pointers with system verilog class handles.
By default all the class varialbes (properties) are visible outside. We can access any properties using the dot operator like m1.addr. But if you want to restict the access from outside you can use the local keyword.
like :
local int addr;
So the statement like objname.addr will cause a error. The feature is called encapsulation. You hide you properties and provide methods to manipulate them
01.
`define ADDR_SIZE 32
02.
`define DATA_SIZE 16
03.
04.
class
mem_transfer;
05.
06.
rand
local
bit
[`ADDR_SIZE-1:0] addr;
07.
rand
bit
[`DATA_SIZE-1:0] data;
08.
09.
rand
bit
[`DATA_SIZE-1:0] write_enable;
10.
rand
bit
chip_enable;
11.
12.
rand
int
unsigned size;
13.
14.
constraint c_size {
15.
size inside {1, 2, 4, 8};
16.
}
17.
18.
constraint c_chip_enable {
19.
chip_enable == 0;
20.
}
21.
22.
// Class Constructor
23.
function
new
(
bit
[`ADDR_SIZE-1:0] addr_in ) ;
24.
addr = addr_in;
25.
data = 'b0;
26.
endfunction :
new
27.
28.
// function print
29.
30.
function
void
print ();
31.
$display (
"Addr = %h, Data = %h, WriteEnable = %h"
, addr, data, write_enable);
32.
endfunction
33.
34.
35.
endclass
: mem_transfer
36.
37.
program test ;
38.
39.
mem_transfer m1;
40.
initial
41.
begin
42.
m1 =
new
('hFFFF);
43.
m1.print();
44.
end
45.
46.
endprogram
47.
48.
Compile :
49.
vlib work;
50.
vmap work work
51.
vlog -sv simpleClass.sv
52.
vsim -c test
53.
54.
Output :
55.
# Addr = 0000ffff, Data = 0000, WriteEnable = 0000