What is Encapsulation? #
Encapsulation is an object-oriented programming concept where internal class details (properties and methods) are hidden from outside access. It promotes data protection, modularity, and controlled access to sensitive parts of a class.
Access Control in SystemVerilog Classes #
In SystemVerilog, class properties are public by default — meaning they can be accessed directly using the dot (.
) operator from outside the class.
To restrict access, SystemVerilog provides two access modifiers:
Modifier | Accessible From | Description |
---|---|---|
local | Only within the same class | Hides data completely from outside and child classes |
protected | Same class and subclasses | Allows access in child classes, but not from the testbench or other modules |
Access Control Summary
Modifier | Same Class | Subclass | Outside Class |
---|---|---|---|
1. Public (default) | ✅ | ✅ | ✅ |
2. Protected | ✅ | ✅ | ❌ |
3. Local | ✅ | ❌ | ❌ |
1.Public : Members are accessible from outside (default in SystemVerilog).
class Packet;
int id; // Can be accessed from outside
function void display();
$display("ID = %0d", id);
endfunction
endclass
module tb;
initial begin
Packet pkt = new();
pkt.id = 5; // Accessing public variable
pkt.display();
end
endmodule
2.Protected : Members are accessible in the class and its subclasses only.
class Base;
protected int id = 42;
function void display();
$display("Base ID = %0d", id);
endfunction
endclass
class Derived extends Base;
function void show_id();
$display("Derived accessing ID = %0d", id); //Allowed
endfunction
endclass
module tb;
initial begin
Derived d = new();
d.show_id(); //Works
// d.id = 10; //Error: 'id' is protected
end
endmodule
3.Private: Class data members and methods are accessible only inside the class where it is defined and not accessible from outside the class or in derived classes.
class A;
private int x = 42;
function void show();
$display("x = %0d", x); //Allowed
endfunction
endclass
class B extends A;
function void try_access();
$display("x = %0d", x); //Error: private member not accessible
endfunction
endclass