Navigating the Initialization Maze: Unraveling the Order of Execution in SystemVerilog Classes

In the below code a member of a class is initialised in a fun way

A a = A::build(this)

Static function is called at declaration of a variable which takes "this" object reference to get access to other variables of "this" object. Take a look at the code and answer what values string variables of class A object will hold at the end?

class P;
  string name;
  function new(string name);
    this.name = name;
  endfunction
endclass

typedef class B;

class A;

  string name;
  string name1;

  function new();
  endfunction

  static function A build(B h);
    A _a = new();
    _a.name = h.name;
    _a.name1 = h.name1;
    return _a;
  endfunction
endclass

class B extends P;

  string name1;

  A a = A::build(this);

  function new(string name);
    super.new(name);
    this.name1 = "test";
  endfunction
endclass

class TEST;
  B b;
  task run();
    b = new("b_obj");
    $display("a.name=%0s", b.a.name);
    $display("a.name1=%0s",b.a.name1);
  endtask
endclass


program top;
  TEST t;

  initial begin
    t = new();
    t.run();
  end
endprogram        

The line A a = A::build(this); is part of the class member initialization. This line is executed when an object of class B is created, and it's executed after the super.new(name) call in the constructor of class B. However, it's important to note that this line is executed during the initialization phase, and the constructor of class B has not completed its execution at this point.

When A::build(this) is called, it's called with a partially initialized object of class B. The this pointer refers to the current instance of class B, but the constructor of class B has not yet finished its execution. Therefore, the name1 member of class B has not been initialized at the time A::build(this) is called. But name member of parent class P has already been initialised.


In SystemVerilog, the order of execution during the creation of an object involves several steps. Let's break down the order of execution in the above code:

  1. Memory allocation: Memory for the object is allocated.
  2. Base class constructor: The constructor of the base class (P) is called using super.new(name) (The new method of a derived class shall first call its base class constructor)
  3. Member variable initialization: Member variables of the derived class (B) are initialized (After the base class constructor call (if any) has completed, each property defined in the class shall be initialized to its explicit default value or its uninitialized value if no default is provided.)
  4. Derived class constructor: The constructor of the derived class (B) is executed, initializing name1 to "test" (After the properties are initialized, the remaining code in a user-defined constructor shall be evaluated)


P.S. Large language model helped me to come up with the title for this article ??

要查看或添加评论,请登录

Grigory Zhikharev的更多文章

社区洞察

其他会员也浏览了