Search code examples
classverilogsystem-verilog

Class object inside program block in system verilog


Can we create a class object inside the program block in sv? I want to create a transaction class handle inside my test written in the program block.

class MyClass; 
  // Class definition here
endclass

program MyProgram;
  initial begin
    MyClass myObj; // Instantiate an object of MyClass

    // Use the class object within the program block
    myObj = new;
    myObj.someMethod(); // Call a method of MyClass

    // Perform other operations with myObj

  end
endprogram

Solution

  • A program block can refer to things outside its scope just like a module. The reverse is not true—you cannot refer to anything declared in a program block from outside of it. But there is nothing preventing you from constructing a class object in a program block and using its handle outside the program block as long as the class is declared outside the program block. The reactive region scheduling semantics of procedural code gets determined by process created by the initial block, not where the code is declared.

    I strongly recommend against the use of program blocks and use a module instead. See https://blogs.sw.siemens.com/verificationhorizons/2009/05/07/programblocks/