oop - Which languages allow to change identity of an object (not cast)? -


in this post, brave wants (in c++) downcast object of type base derived type. assuming derived type has no more attributes base, can make sense if you're jealous of methods derived class provides.

are there programming languages allow such thing?

actually, done without problem in common lisp, , in other lisp dialects clos (common lis object system) ported. use change-class generic function that.

clos works multiple dispatch methods, method not tied class or object, it's function chosen in group of similar functions wrt types (or identities) of arguments. when using change-class, can give arguments if creating new instance, , data stored in object remain. here little session shows how works:

cl-user> (defclass base ()        ((name :initarg :name))) #<standard-class base> cl-user> (defclass derived (base)        ((age :initarg :age :initform 0))) #<standard-class derived> cl-user> (defvar foo (make-instance 'base :name "john doe")) foo cl-user> (change-class foo 'derived :age 27) #<derived {100338f2d1}> cl-user> (with-slots (name age) foo        (list name age)) ("john doe" 27) cl-user> (defvar bar (make-instance 'base :name "baby joe")) bar cl-user> (change-class bar 'derived) #<derived {10036cf6e1}> cl-user> (with-slots (name age) bar        (list name age)) ("baby joe" 0) cl-user>  

if default behaviour not enough, may define method on update-instance-for-different-class.

so yeah, there programming languages allow such thing!


Comments

Popular posts from this blog

c# - how to write client side events functions for the combobox items -

exception - Python, pyPdf OCR error: pyPdf.utils.PdfReadError: EOF marker not found -