SystemVerilog Datatype: Class (Part 2)

Previous: Object Properties and Object Methods | Next: Doing more with Constructors.

Last time, in Part 1 of this series, we discussed the basic definitions and structures of a class data type. We learnt about object instance and object handle and various intricasies about object properties and object methods . Lastly, we went to into static class properties and static class methods. This background gives us a good head start to explore other fun stuffs.

We will start with the concept of Constructors.

Constructors

Recall from our earlier discussion how we initialize an object at the time of its declaration.

   Triangle t = new;

The function new is called a class constructor, or simply, constructor.

Now look back at the definition of the function new() reproduced below:

class Triangle; 
   ... 
   function new()
   ... // all initializations go here
   endfunction
   ...
endclass

One thing that stands out in the above definition is that a constructor function does not have a return type. When you use a constructor, the left hand side of the assignment determines the return type.

Myths and misconception surrounding constructors are abound. We will try to disspell some of them here.

  • "I must have a constructor for each class that I define."

    It is not illegal not to have a constructor for each class, though having one will be a good practice for your peace of mind.

    As a matter of fact, whether you have a class-specific constructor or not, by default, every class has a built-in constructor. This built-in constructor assigns each member to its uninitialized value (e.g., x for a wire, 0 for a real etc.).

  • "I must name my constructor as 'new'."

    Although it is customary to name a constructor as 'new', any other name is fine too.

     
          Triangle t = my_new();
       

  • "I can not pass any argument to new()."

    On the contrary, it is always a good idea to make your constructor flexible by passing arguments to it. For example, we can customize our own new() defined within Triangle as:

     
          Triangle t = new(first_arg, second_arg, last_arg);
       

    Corresponding to this, the definition of new() within the class Triangle will look like (with arbitrarily chosen types for first_arg, second_arg, etc.):

     
          function new (int first_arg, time second_arg, bit third_arg);
          ... // rest of the definition goes here
          endfunction
       

Interestingly, you can use these simple concepts about constructors to build powerful sequences that handle complex handles. We will see some this on the next page.

Previous: Object Properties and Object Methods | Next: Doing more with Constructors. Share/Save/Bookmark




Verification Management
Join Verification Management Group


Shop Amazon - Contract Cell Phones & Service Plans

Book of the Month