System Verilog Encapsulation





Data Hiding and Encapsulation

As for above codes and their outputs data inherited from the parent were visible to the world outside. One object can access others data. Even the super command gave all the permissions to access the codes. Yes that sounds like a science fiction movie where super keyword can access J.A.R.V.I.S database but J.A.R.V.I.S has to smart enough to determine which data has to be protected and must remain only within the object who have the permission. This makes the programmers to dive into a security mechanism to hide the data from other class member. This is what we call encapsulation.

System Verilog has all its class members in default as public. It can be made private by declaring it as either local or protected. A local variable cannot be inherited by its subclass members. It’s not visible within the subclass and remains inside the parent class so accessing it outside parent class would result in an error whereas a protectedkeyword can be inherited but it cannot be access from outside of the subclass.

An example will make this more clear
classParent; //Parent Class
  integer x;
  local integery = 16;
  function intover(int a,int b);
    this.x = a*b;
    $display("Result %d",x);
  endfunction:over
endclass:Parent

modulemainishere;
  initial begin
  Parent p = new;
  Parent q = new;
  p.over(12,q.y);
  end
endmodule

An error would pop up regarding Access to local member 'y' from outside a class context is illegal. Since the member y is local thus it cannot be accessed hence this is the true form of encapsulation.
Another example with the use of protectedkeyword.

classParent; //Parent Class
  integer x;
  protected integery = 16;
endclass:Parent

classBen extends Parent;
  task show;
  $display(super.y);
endtask:show
endclass:Ben

modulemainishere;
  initial begin
  Ben B = new;
  B.show();
  end
endmodule

Setting the member “y” Protected will enable the super keyword to access it and output would render 16. Setting it to local will deny the access. Protected members are accessible in the extended class but not outside of the class.

This Keyword

When a class member and task member have same reference then this keyword is used for assigning value. This keyword always points to the predefined class member and not to the called member.

For example

classParent; //Parent Class
  integer x;
  task thiskeyword(int x);
     this.x = x;
  endtask
endclass:Parent

This.x = x is the syntax here. The LHS points to the class member x of the  2nd line and the RHS points to the task member.
The predefined class member can be of local, protected or statictype. The called member cannot be static here. An error would be thrown in the former case pretty similar to this






  

No comments:

Post a Comment