System Verilog introduced Object-Oriented Programming (OOP) concepts to enhance its capabilities for designing and verifying complex systems. Classes are a cornerstone of these OOP features, providing a way to encapsulate data (properties) and functions (methods) together.
In this article, we’ll discuss how to declare a class, create objects, and access properties and methods in System Verilog, with practical examples to clarify each concept.
What is a Class in SystemVerilog?
A class in SystemVerilog is a blueprint for creating objects. It defines:
- Properties: Variables that hold data.
- Methods: Functions or tasks that perform operations on the properties or provide functionality.
Classes support inheritance, polymorphism, and other OOP principles, making them highly versatile for verification purposes, especially in UVM (Universal Verification Methodology).
Declaring a Class
A class is declared using the class keyword, followed by its name. Properties and methods are defined inside the class.
Syntax:
class ClassName;
// Properties (variables)
data_type property_name;
// Methods (functions or tasks)
return_type method_name();
// Method body
endfunction
endclass
Example:
class Car;
// Properties
string brand;
int speed;
// Method to display car details
function void display();
$display("Brand: %s, Speed: %0d", brand, speed);
endfunction
endclass
Here, the Car class defines two properties: brand (string) and speed (integer), along with a method display() to print the details.
Creating Objects
An object is an instance of a class. To create an object, we use the new keyword.
Syntax:
ClassName object_name = new();
Example:
Car myCar; // Declare an object
myCar = new(); // Create (instantiate) the object
After creating the object, we can access its properties and methods.
Accessing Class Properties and Methods
Properties and methods of a class are accessed using the . (dot) operator.
Example:
module testbench;
initial begin
// Create an object of the Car class
Car myCar = new();
// Assign values to properties
myCar.brand = "Tesla";
myCar.speed = 120;
// Call the method to display details
myCar.display();
end
endmodule
Full Code:
class Car;
// Properties
string brand;
int speed;
// Method to display car details
function void display();
$display("Brand: %s, Speed: %0d", brand, speed);
endfunction
endclass
module testbench;
initial begin
// Create an object of the Car class
Car myCar = new();
// Assign values to properties
myCar.brand = "Tesla";
myCar.speed = 120;
// Call the method to display details
myCar.display();
end
endmodule
Output:
Brand: Tesla, Speed: 120
