0

What is wrong with the following code.

program test;

class a;
    const int i;
endclass : a

class b extends a;
    function new();
        i = 10;
    endfunction : new
endclass : b

class c extends a;
    function new();
        i = 100;
    endfunction : new
endclass : c

initial begin
    b bo = new();
    c co = new();
    $display(bo.i, co.i);
end

endprogram : test

I get the following compile error

Invalid initialization of instance constant: 'i' cannot be initialized

more than once in constructor. There is a potential re-initialization

at statement : this.i = 10; Previous at: test.sv,9 Source info:

this.i = 10;

1
  • My question is different. Won't the both inherited classes get a copy each of the constant variable Commented Mar 22, 2020 at 17:55

1 Answer 1

1

You can only make one assignment to a const variable during the construction the the class object. That has to come as either part of its declaration, or assigned during its it corresponding constructor method. Even though you didn't write an explicit constructor method in class a, SystemVerilog creates an implicit one for you. You did neither, so its initial value is 0. The only way to override an instance constant's value is by passing it as a constructor argument, or parameterization.

class a;
    const int i;
    function new(int aa = 10);
      i = aa;
    endfunction
endclass : a

class b extends a;
    function new(int aa=100);
        super.new(aa); // super.new(); is implicitly added if you don't
    endfunction : new
endclass : b
class c extends b;
    function new();
        super.new(500); // super.new(); is implicitly added if you don't
    endfunction : new
endclass : b

Also note that it is now illegal to initialize variables when they are implicitly declared as static varibles inside procedural code. You should move them outside the begin/end block, or add an explicit lifetime using the static or automatic keywords.

b bo = new();

initial begin
    static c co = new();
    $display(bo.i, co.i);
end

It makes a big difference of the declaration was inside a procedural loop.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the clarification. I got it working now. However, I do not understand the edit you made program -> module and the stuff with static or automatic. I got it working with just super.new(10) and super.new(100)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.