SystemVerilog Datatype: Class (Part 3)
Previous: Class scope resolution
Classes with Parameters
Similar to a module or a function, a class can be parameterized. The
rationale behind parameterizing a class is also the same: it allows
you to avoid writing repeatative code that are similar to each other
but differ only in certain parameters.
A common example of a parameterized class is where the bitwidth of
one or more of its vector properties depend on a parameter.
class Triangle (int colordepth = 24);
bit [(colordepth-1):0] red;
bit [(colordepth-1):0] green;
bit [(colordepth-1):0] blue;
...
endclass
In SystemVerilog, a class parameter is not restricted to be just
values, it can be a type too. This opens up possibility of powerful
customization of code based on parameter type. The following example
shows this.
class Triangle #(type T = bit);
function T isFilled()
... // details here
endfunction
...
endclass
Now, the class Triangle can be instantiated with any arbitrary type.
This enables u to change the return type of the function based on
parameter. In the first example below, t1 returns a bit
vector, whereas t2 returns an int.
Triangle #(bit [1:0]) t1;
Triangle #(int) t2;
Summary
In this part we learnt about data encapsulation and various ways of
limiting access to a member of a class. We talked about polymorphism
and the class scope resolution operator (::). Finally, we saw how
parameters can be used to customize classes.
Class datatype brings to SystemVerilog what its counterpart brought
to C++. An object oriented approach is particularly useful to design,
say, a testbench, that has multiple independent functions, to be
designed by a diverse and, perhaps, geographically separated team - a
reality of today.
This concludes our discussion on SystemVerilog class datatype, a part
of Project VeriPage SystemVerilog Datatype series. Stay
tuned for more articles in this series in the future.
Previous: Class scope resolution
|