Upcasting in SystemVerilog

Viewed 109

I'm trying to understand Upcasting and Downcasting in SystemVerilog. Upcasting is casting to a supertype, while downcasting is casting to a subtype. Upcasting is always allowed, but Downcasting involves a type check.

So I made a simple test code for upcasting and downcasting.

1.Test for upcasting.

class animal;
  function void eat();
    $display("eat");
  endfunction
endclass

class dog extends animal;
  function void bark();
    $display("woof");
  endfunction
endclass

class cat extends animal;
  function void meow();
    $display("meow");
  endfunction
endclass

module test;
  animal a1,a2;
  dog d1, d2;
  cat c1, c2;
  initial begin

    a1=new();
    d1=new();
    c1=new();
    
    d1.eat();
    c1.eat();
    
    d1.bark();
    c1.meow();
    
    c1 = d1;
    c1.bark(); //bark is not a class item.
    
    d1 = c1;
    d1.meow(); //meow is not a class item.
    
    a1 = d1;
    a1.bark(); //bark is not a class item.
    
    a1 = c1;
    a1.meow(); //meow is not a class item.
    
    
  end
endmodule

In the class animal, dog and cat, I need to use bark and meow function from a derived dog and meow class. So I declared as the below But I got the compile error

    c1 = d1;
    c1.bark(); //bark is not a class item.
    d1 = c1;
    d1.meow(); //meow is not a class item.
    a1 = d1;
    a1.bark(); //bark is not a class item.
    a1 = c1;
    a1.meow(); //meow is not a class item.

As I know, the base class want/need to a properties from a derived class then we do upcasting. How do I get c1's bark(), d1's meow(), a1's bark(), a1.meow()?

1 Answers

If you comment out all the lines after c1 = d1;, you get a more helpful error message:

    c1 = d1;
          |
xmvlog: *E,TYCMPAT: assignment operator type check failed 
(expecting datatype compatible with 'class $unit::cat' but found 
'class $unit::dog' instead).

This gives you the reason why bark is not a class item: the assignment failed because c1 is not the same type as d1.

The VCS simulator behaves the same way, and produces a similar compile error.

Related