SystemVerilog classes

 Classes 


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 methods, both are members of the class.
classes allow objects to be dynamically created, deleted, assigned, and accessed via object handles.

 Class Declaration 

Below is the simple class declaration example, it 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 

as we know class is a data type, variable can be declared with the class type.
     sv_class class_1;

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

class properties and methods can be accessed only after creating the object.
     class_1 = new();

above statement will creates an object and assign its handle to class_1.
    sv_class class_1 = new();


above statement will do both declaration of variable and object creation.


 Accessing class properties and methods: 

class properties and methods can be accessed by using object name 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(););


 Example -1 


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
Execute the above code on