I have been thinking about a way solve a problem I have and I’m not sure whether it will work or not.
Say we have a base class called A and 3 subclass B,C and D.
A
^
-----------------
| | |
B C D
Also we have three classes X, Y and Z.
On my system objects type B,C,D are passed as type A and usually I have to convert the Objects of type B,C,D to either objects X,Y or Z (That’s not a cast, I manually convert them since they are totally different).
Therefore, to convert an Object type A to a type X, Y or Z I need to check the subtype first and then initialize a X, Y or Z Object with the result of some operations about the A Object depending on the subtype.
I thought about overloading an explicit cast operation from A to X, Y or Z just doing the same process I was doing when I converted them, but then I thought… Would it be possible to use polimorfism and overload the cast from B,C and D in some way that when I add a new subtype of A I do not need to change the cast code of A?(Just add the explicit cast overload to the new subtype)
I hope I have explained myself properly sorry if there is something confusing.
NOTE: I will add a cast overload for X,Y,Z
You can have your cast operator for type
Acall a virtual (or abstract?) instance method of yourAinstance and override that for each subclass ofA.X,YandZshould derive from a mutual base class for this solution, though, so the cast operator can have that base class as a result type.In this example,
Wis a base class ofX,YandZ.