Ready-to-run snippets

Code Examples

Ready-to-run Verilog, SystemVerilog, and UVM examples. Click any to open it live in the IDE.

← All examples

When Accessed From Outside The Class

SystemVerilog Advanced Features

A second take on local vs public members: the local variable prints fine from inside display() but not when accessed as abc.local_var outside the class.

Open in IDE
testbench.sv
class ABC;
  // By default, all variables are public and for this example,
  // let's create two variables - one public and the other "local"
  byte  	  public_var;   
  local byte local_var; 	
  
  // This function simply prints these variable contents
  function void display();
    $display ("public_var=0x%0h, local_var=0x%0h", public_var, local_var); 
  endfunction
endclass

module tb;
  initial begin
    
    // Create a new class object, and call display method
    ABC abc = new();
    abc.display();
    
    // Public variables can be accessed via the class handle
    $display ("public_var = 0x%0h", abc.public_var);
    
    // However, local variables cannot be accessed from outside
    $display ("local_var = 0x%0h", abc.local_var);
  end
endmodule



/*
Simulation Log:
---------------

irun: 15.20-s038: (c) Copyright 1995-2017 Cadence Design Systems, Inc.
    ABC abc = new();
            |
ncvlog: *W,VARIST (testbench.sv,17|12): Local static variable with initializer requires 'static' keyword.
    $display ("local_var = 0x%0h", abc.local_var);
                                               |
ncvlog: *E,CLSNLO (testbench.sv,24|47): Access to local member 'local_var' in class 'ABC' is not allowed here.
irun: *E,VLGERR: An error occurred during parsing.  Review the log file for errors with the code *E and fix those identified problems to proceed.  Exiting with code (status 1).
*/
design.sv
// Code your design here
Admin mode — edit and delete controls are visible on each row. Use the IDE to add new snippets via File → Save as Snippet.