Subclass Type
    Mason Green 
    mason.green at gmail.com
       
    Fri Aug 15 05:40:24 PDT 2008
    
    
  
Hi, does anyone know how to return a Subclass's type?  I would like to create a new instance of the subclass based on its type. Here is my example code....
class FooBar {
 
class Foo : FooBar {
       
    this() {
        super(1);
    }
    
    override void printKey() {
        Stdout(key).newline;
    }    
    
}
class Bar : FooBar {
    this() {
        super(2);
    }
    
    override void printKey() {
        Stdout(key).newline;
    }
}
void main() {
    FooBar x = new Foo();
    FooBar y = new typeof(x);
    
    x.key++;
    y.printKey(); // This prints 0. I want it to print 1
    
}
As is, y is created as type FooBar.  Instead I would like to be of type Foo. i.e the equivalent of:
FooBar y = new Foo();
I've seen this done in other languages such as ActionScript fairly easily:
public function createJoint(data:JointData):Joint
{	
    var c:Class = data.getJointClass();		
    var j:Joint = new c(data) as Joint;
}
In this case, Joint is the superclass.  data.getJointClass returns the subclass type.  j is created as a new subclass. The normal D equivalent would be:
Joint j = new MouseJoint();  // or some other subclass that getJointClass     
                                        // returns.
Thanks,
Mason
    
    
More information about the Digitalmars-d-learn
mailing list