1

I was working on checking my understanding on polymorphism with constraints. I wrote a sample code

class parent;
  rand int unsigned a;
  constraint a_c { a < 1000;}
  function print();
    $display("The randomized data is %d\n", a);
  endfunction
endclass

class child extends parent;
  constraint a_c { a > 50;}
endclass

module m;
  child c = new();

  initial begin
    c.randomize();
    c.print;
  end
endmodule

The output was

The randomized data is 2567677

What is going wrong here?

1
  • Looks like expected behavior. testbench.in/CR_08_CONSTRAINT_BLOCK.html --> Constraints in derived class with the same name in base class overrides the base class constraints just like task and functions. Commented Jul 1, 2016 at 2:47

1 Answer 1

6

That is a valid result that satisfies constraint a_c { a > 50;} Since you extended constraint a_c, it overrides the constraint in the base class. If you want the constraint to be additive, you need to give it a different name from the base class.

BTW, I suggest avoiding the terms parent and child when referring to OOP inheritance. Those terms imply distinct objects. Use base/super and derived/extended classes instead.

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

1 Comment

+1 just for this..."BTW, I suggest avoiding the terms parent and child when referring to OOP inheritance. Those terms imply distinct objects."

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.