In reply to Sagar Shah:
Sagar,
Read the links provided by Dave thoroughly and experiment as much as you can, then you’ll figure out the answer yourself.
I am trying to explain this in a slightly different manner, hoping it helps you understand the concept easily.
- A class is a user defined data type. The size of class object (created using new()) depends on the members of the class. In SV, a class object is always pointed using a handle (unlike pointers in C).
- In your example, any object of class Base requires 4 bytes (for int unsigned b). So the class handle B can only point to an object of 4 bytes (and not more than that).
- Where as, any object of class Derived requires 8 bytes (for both b, d). So the class handle D can point to an object of 8 bytes.
- When we assign a derived handle to base handle using $cast(B, D), though B is still pointing to the derived object we are essentially losing access to 4 bytes that are additionally added as part of the derived class (as B handle can point only to 4 bytes as mentioned in point (2)). That is the reason you get the error. Since you are losing access to the information, you call it as downcast.
- In order to assign a derived handle to base handle B = D, $cast is not required at all i.e., B=D is as good as $cast(B, D).
- $cast is used in cases where a base handle is to be assigned to the derived handle (given that the base handle already points to a derived object).
Ex:
Base B;
Derived D;
D = new(); // 8-byte object created and pointed by handle D
B = D;
$cast(D, B); // Works fine, as B already pointing to an object of Derived class that is of 8 byte.
B = new(); // B now started pointing to an object of type Base Class which is only of 4 bytes
$cast(D, B); // ERROR:Type Compatibility issue, as B is pointing only to a 4-byte object here, so we cannot assign to an 8-byte handle as the details of the other 4-bytes is unknown.
Thanks