Regarding Method Overriding / Polymorphism SystemVerilog

In reply to ziggy:

$cast does not create or copy objects; it tries to copy a handle from one class variable to another. Please see my course on SystemVerilog OOP, especially the second session.

In reply to dave_59:

So in the above code I have posted, Class A’s handle ‘a’ is created by ‘new’. Then I do a $cast(b,a). Why is there an error ‘type mismatch’?

But the following code works and why is that?


class A;
   int a=10;
   virtual function void disp();
     $display("Base a=%d",a);
   endfunction
endclass
 
class B extends A;
  int a=20; 
  function void disp();
    $display("Derived a=%d",a);
  endfunction
endclass
 
module tb();
  A a;
  B b=new;

  initial begin
    b=a;
    $cast(b,a);
 
    b.disp();               //
    $display("b.a=%d",b.a); // 
    a.disp();               //
    $display("a.a=%d",a.a); //  
  end
 
endmodule

In reply to ziggy:

The code you just posted does not work. Did you simulate it?

b=a; // should give you a compile error

b.disp(); // should be a run time fatal because b has a null handle.

In reply to dave_59:

Sorry it was a typo
Its “a=b” and not “b=a”

In reply to ziggy:

Have you looked at my course yet?

In reply to dave_59:

Hi Dave,
Your sv-class-OOP courses are excellent !! Heavily loaded with important information. The way you described all of them seamlessly is awesome!