SystemVerilog classes

SystemVerilog Class

A class is a user-defined data type that includes data (class properties), functions and tasks that operate on data.

functions and tasks are called as methods, both are members of the class.classes allow objects to be dynamically created, deleted, assigned and accessed via object handles.

Class Declaration

Class declaration example

The below class has one data property x and two methods set and get.

class sv_class;
  //class properties
  int x;

  //method-1
  task set(int i);
    x = i;
  endtask

  //method-2
  function int get();
    return x;
  endfunction
endclass

Class Instance and Object Creation

Class declaration/Class Instance

As we know the class is a data type, Declaring class type variable is similar to declaring other variables.

sv_class class_1;

the above statement shows the declaration of variable class_1 with the type sv_class.
In other words, variable class_1 can contain a handle to an instance of the class sv_class.

Object Creation

Class properties and methods can be accessed only after creating the object.

class_1 = new();

the above statement will create an object and assign its handle to class_1.

sv_class class_1 = new();

the above statement will do both declarations of variable and object creation.

Accessing class properties and methods

Class properties and methods can be accessed by using object names followed by property or method name.

class_1.set(10); //calling set method to set value 10 to x
$display("Vlaue of x = %0d",class_1.get(););

Class example

class sv_class;
  //class properties
  int x;

  //method-1
  task set(int i);
    x = i;
  endtask

  //method-2
  function int get();
    return x;
  endfunction
endclass

module sv_class_ex;
 sv_class class_1; //Creating Handle

  initial begin
    sv_class class_2 = new(); //Creating handle and Object
    class_1 = new(); //Creating Object for the Handle
    //Accessing Class methods
    class_1.set(10);
    class_2.set(20);
    $display("\tclass_1 :: Value of x = %0d",class_1.get());
    $display("\tclass_2 :: Value of x = %0d",class_2.get());
  end
endmodule

Simulator Output

class_1 :: Value of x = 10
class_1 :: Value of x = 20

Click to execute on

❮ Previous Next ❯