Matthew
Matthew

Reputation: 13937

Why can't I call a constructor outside an initial or always block?

I tried to run this code using Synopsys VCS:

class parent;
int a = 10;
endclass

class child extends parent;
int b = 10;
endclass

module main;
  parent P;
  child C;

  P = new();
  C = new();

  initial begin
    $display("a=%d\n",C.a);
  end
endmodule

It is giving an error at the object creation after the handle declaration. The error is as follows:

Error-[SE] Syntax error Following verilog source has syntax error : "class.sv", 20: token is '=' P = new();

However, when I change the module "main" to this

module main;
  parent P = new();
  child C = new();

  initial begin
    $display("a=%d\n",C.a);
  end
endmodule

I get no such error. Why is this?

Upvotes: 0

Views: 667

Answers (1)

Matthew
Matthew

Reputation: 13937

The error is caused by the fact that these two lines:

P = new();
C = new();

are procedural code - they must be inside an initial or always block. They are procedural code, because they call a function - the constructor "new".

These two lines, however, are declarative code:

parent P = new();
child C = new();

and so they are legal outside an initial or always block. They are declarative code because they declare two objects (P of class parent and C of class child). These objects are also initialised by calling their constructors. These two objects have module scope - they will be visible throughout the module.

It is also legal to put these two lines of code inside an initial or always block (as long as they appear before any procedural code). In that case, the two objects will have block scope - they will only be visible inside that block.

Upvotes: 2

Related Questions