Ad Code

Responsive Advertisement

Ticker

6/recent/ticker-posts

Classes and Constructors in SystemVerilog with Example

 

🌟 Understanding Classes and Constructors in SystemVerilog with Example

📘 Introduction

SystemVerilog is an object-oriented hardware description and verification language. One of its powerful features is classes, which allow modeling complex behaviors and reusable components. In this post, we’ll explore:

  • How to define a class

  • The use of constructors (new) and user-defined functions

  • Object creation and null checks


🧱 What is a Class in SystemVerilog?

A class in SystemVerilog is a blueprint for creating objects. It can contain data members (variables) and functions (methods) that operate on those members.


🔧 Code Explanation

Let’s look at an example class called sample:

class sample;

  int a;

  bit b;

  

  // Default constructor (called when new object is created)

  function new(int const_a, bit const_b);

    a = const_a;

    b = const_b;

    $display("Inside new constructor: a = %0d, b = %0b", a, b);

  endfunction

  

  // User-defined method to assign new values

  function user_def(int const_a, bit const_b);

    a = const_a;

    b = const_b;

    $display("Inside user-defined constructor: a = %0d, b = %0b", a, b);

  endfunction

endclass

📍 Key Points:
  • The new function is the constructor. It is automatically called when an object is created using new().

  • user_def is just a normal function to assign new values after creation.


🔁 Object Creation and Method Call Example:

module class_sample;
  sample tr1, tr2; // Declare object handles
  initial begin
    tr1 = new(5, 0);          // Constructor is called
    tr1.user_def(10, 1);      // Method call to update values
    
    $display("Current values: a = %0d, b = %0b", tr1.a, tr1.b);
    
    // Check if object is created before calling method
    if (tr2 != null)
      tr2.user_def(3, 1);
    else
      $display("tr2 object is not created");
  end
endmodule


Expected Output:

Inside new constructor: a = 5, b = 0

Inside user-defined constructor: a = 10, b = 1

Current values: a = 10, b = 1

tr2 object is not created

🎯 Conclusion

  • Constructors in SystemVerilog (new) are used for object initialization.

  • You can define multiple methods like user_def for flexibility.

  • Always check if an object is null before using it.

This simple example introduces you to SystemVerilog OOP concepts, useful in UVM and advanced verification environments.



Post a Comment

0 Comments

Ad Code

Responsive Advertisement