When overriding a virtual function in a subclass, the overridden function must have the exact same return type as the one the parent virtual function does. For example, the following ZScript will not compile:
Code: Select all
class Base1
{
virtual Base2 GetSomething()
{
return null;
}
}
class Child1 : Base1
{
override Child2 GetSomething() // Script error: Attempt to override non-existent virtual function GetSomething
{
return null;
}
}
class Base2
{
}
class Child2 : Base2
{
}
Allow the return type of the overridden function to be either the same as, or a subtype of the parent function's return type.
Justification:
Imagine I'm working with an instance of Child1. If I needed to make use of the extra functionality of the type Child2 that is returned by Child1::GetSomething, the only solution would be to cast the returned Base2 to Child2. This breaks encapsulation and is also dangerous, because if Child1::GetSomething is changed to return something other than a Child2, the cast will return null, and a VM abort could be triggered.
However, if Child1 could advertise right away that its GetSomething returns not just a Base2 but actually a Child2, then changing the return type would trigger a compile error, which could make it easier to avoid potential bugs.