public class Derived : BaseClass
{
public Derived(string name) : base(name) {}
public static implicit operator BaseClass(Derived derived)
{
return new BaseClass(derived.ColorHex);
}
public static implicit operator Derived(BaseClass baseclass)
{
return new Derived(baseclass.name);
}
}
This won’t work. why isn’t it allowed?
I can potentially write the logic necessary for it to make sense, especially when converting from the base to the derived one.
EDIT:Changed the title of the question
Because there is already an implicit conversion from
DerivedtoBaseClass, and the converse does not make any sense.Regarding the latter: if your
Baseobjects are meant to be implicitly convertible toDerived— why aren’t theyDerivedobjects in the first place?Obligatory quotes from the standard:
This says there’s an implicit conversion
Derived=>Base, as we all know.This says there’s already an explicit conversion
Base=>Derived(which is what allows you to try downcasting at runtime).And this says that since the two conversions of interest are already defined by the language, you can’t redefine them.