I have had several situations when i would like to do that. This could be an example:
Consider a possible implementation for the chess game. We define the abstract class ‘Piece’ and classes inheriting from it: ‘bishop’ ‘peon’ ‘tower’ ‘horse’ ‘queen’ etc
We may have our peon about to reach the end of the board, and it may be required for a method called onto that peon object to change the class of that object to ‘Queen’, ‘horse’ or whatever.
So my question is, is there any way to do that in C++ or Java? If not, in any other language?
Also, are there other approaches for this situations in general?
You might be able to use the decorator pattern or the strategy pattern.
With decorator:
When needed you replace the
Pawninstance with theDecoratedinstance. So it still involves replacing one instance with an other as mentioned in OpenSause’s answer.When you plan ahead you can use strategy it is still not really changing classes: