SystemVerilog Datatype: Class (Part 2)

Previous: Constructor | Next: Inheritance

Doing More with Constructors

Combining class type of variable declaration and class constructor gives rise to interesting scenarios. Let us consider few such cases.

Code Snippet 1:

 
   Triangle t1; 

A variable t1 of type Triangle is created. It is yet to be initialized and has a value of null.

Code Snippet 2:

 
   Triangle t1 = new; 

An instance of type Triangle is created and t1 contains an actual object handle.

Code Snippet 3:

 
   Triangle t1 = new; 
   Triangle t2; 
   t2 = t1;

Only one instance of object of type Triangle is created. This object can be referred to either with the name t1 or t2.

Code Snippet 4:

Lastly,

 
   Triangle t1 = new; 
   Triangle t2 = new t1; 

This time a copy of t1 is made and a new object t2 is created. This is known as shallow copy. All class properties of t2 are exact replicas of t1, except for objects. For object, only the object handles are copied. This means, after a shallow copy, both the original and the copied version of the object will share the same object handle. This is why it is called 'shallow' copying. To have separate object handles as properties of t1 and t2, you typically need to have custom code.

Constructors, Lord Brahma, Lord Vishnu and Lord Maheswara

Some languages force you to manage memory allocation for variables. C++, for example, has the concept of a destructor function that de-allocates memory earlier assigned by a constructor function of a class.

While this type of restriction imposes discipline in programming, it also makes the job of code maintenance a bit difficult (since you need to keep track of memory allocation for each and every class).

SystemVerilog adopts a simpler strategy: whenever the use of a variable (or object) ends, the SystemVerilog compiler automatically de-allocates the memory for that variable, thus eliminating constant supervision of the designer.

Previous: Constructor | Next: Inheritance Share/Save/Bookmark




Verification Management
Join Verification Management Group


Shop Amazon - Contract Cell Phones & Service Plans

Book of the Month