Tutorials

Learn More

As discussed earlier, local access qualifiers can not be accessed outside of the class scope. But sometimes it is required to provide class member access to derived classes. This access is provided by a protected access qualifier.

A protected class member can not be accessed outside class scope except access by their child classes.

Protected access Qualifier Example

Protected method access in child class

The protected display method can be accessed in child class which is not possible in the case of local access qualifiers.

class transaction;
  bit [31:0] data;
  int id;

  function new();
    data = 100;
    id = 1;
  endfunction
  
  protected function void display();
    $display("data = %0d and id = %0d", data, id);
  endfunction
endclass

class child_trans extends transaction;
  bit [31:0] addr;
  
  task calc_addr;
    addr = data * id;
    display();  // child class is accessing protected access method of parent class
    $display("addr = %0d", addr);
  endtask
endclass

module class_example;
  child_trans tr;
  
  initial begin
    tr = new();
    tr.calc_addr();
  end
endmodule

Output:

data = 100 and id = 1
addr = 100

Protected method access outside the class scope

A compilation error is expected when the protected display() method is accessed outside the class scope

class transaction;
  bit [31:0] data;
  int id;

  function new();
    data = 100;
    id = 1;
  endfunction
  
  protected function void display();
    $display("data = %0d and id = %0d", data, id);
  endfunction
endclass

module class_example;
  transaction tr;
  
  initial begin
    tr = new();
    tr.display(); // can not accessed outside class scope
  end
endmodule

Output:

tr.display(); // can not accessed outside class scope
     |
 *E,CLSNPO (testbench.sv,22|13): Access to protected member 'display' in class 'transaction' is not allowed here.

System Verilog Tutorials