How $cast will work, when two child classes are extend from single parent class

Hi,

I have a question on $cast.

For example:

class A extends base_class;


endclass // Class A

class B extends class A;


endclass // Class B

class C extends class A;


endclass // Class C

Now my question is

Initial begin
A A1;
B B1;
C C1;
B1=new();
$cast(C1,B1); → Constraint failure.

May i know why i am getting Constraint failure and how to overcome of the above problem.

$cast(B1,A1); → No constraint failure

Thanks and Regards,
Koti

In reply to pkoti0583:

From the SV LRM section 8.16 Casting,

“It is always legal to assign an expression of subclass type to a variable of a class type higher in the
inheritance tree (a superclass or ancestor of the expression type). It shall be illegal to directly assign a
variable of a superclass type to a variable of one of its subclass types. However, $cast may be used to
assign a superclass handle to a variable of a subclass type provided the superclass handle refers to an object
that is assignment compatible with the subclass variable.”

Relationship wise B and C are not related. So you cannot cast two unrelated classes.

But A has a relationship with both B and C i.e A is an ancestor to B and C.

$cast is only needed when you are doing a down-casting i.e during retrieval of a child object from a parent handle.