Down Casting

I have a problem with using $cast

If pc is a parent class and cc is a child class, This creates an error


pc pc;
cc cc;

initial begin
  pc = new();
  $cast(cc, pc);
end

but this doesn’t create errors


pc pc;
cc cc;
cc cc2;

initial begin
  cc = new();
  pc = cc;
  $cast(cc2, pc);
end

I think downcast doesn’t create errors when parent object was upcast before.
Is it right?

In reply to HanP:

Remember that there is a distinction between classes variables and handles to class objects.

A class variable can only store handles to class objects that are the same type or extensions of that type.

$cast is called a dynamic cast because it checks at runtime if the source handle type is the same or an extension of the destination class variable type.

In your first $cast, the source handle type is not an extension of the destination class type, it is the opposite. Therefore an error.

In your second $cast, the source handle type is an extension of the destination class type. Therefore no error.

In reply to dave_59:

Thank you dave.

I already know that the source handle should be an extension of the destination class type.
But, In my second $cast, pc is upcast of cc but pc is the parent class handle of cc2 class.
So, i think pc is still not the extension of the cc class.
Isn’t it right?

Then, Is it impossible that make cc downcast of pc what was not upcast before?

In reply to HanP:

class base;
endclass
class ext1 extends base;
endclass
class ext2 extends base;
endclass

base base_h;
ext1 ext1_h;
ext2 ext2_h;
initial begin
  ext1_h = new;
  base_h = ext1; // upcast
  $cast (ext2_h, base_h); // this is an error even though there was an upcast before.
end