In this post, a brave wants (in C++) to downcast a object of type Base to a Derived type. Assuming that the Derived type has no more attributes than Base, it can make sense if you’re jealous of the extra methods that the Derived class provides.
Are there programming languages that allow such a thing?
Actually, this is something that is done without problem in Common Lisp, and in other Lisp dialects where CLOS (Common Lis Object System) was ported. You use the
change-classgeneric function for that.CLOS works with multiple dispatch methods, so a method is not tied to a class or object, it’s just a function that is chosen in a group of similar functions WRT to the types (or identities) of its arguments. When using
change-class, you can give arguments as if you were creating a new instance, and data already stored in the object will remain. Here is a little session that shows how it works:If this default behaviour is not enough, you may define a method on
update-instance-for-different-class.So yeah, there are programming languages that allow such a thing!