First Steps: Dynamic class instantiation

S. S at s.com
Sun Jan 28 00:32:55 PST 2007


On 2007-01-27 19:30:04 -0800, Thomas <thc at forestfactory.de> said:

> Hi
> 
> I'm just making my first steps to understand D, and sometimes I'm a 
> little bit offroad as I do not know C/C++, just PHP, Javascript etc.
> 
> I would like to write a small shell application with a small bundle of 
> functionalities. As a first step, the user must choose which function 
> to use (I already got that part). Than she must enter some information 
> for the function to work on.
> 
> I thought of doing this by creating classes for each functionality 
> implementing the same interface and creating an array in main() that 
> somehow refers to these classes. There the trouble starts.
> 
> I don't know how to create such an array, and of which type it has to 
> be. To be more specific, I provide you with a PHP example of what I 
> want to do:
> 
> $selected = 1;
> $classes = array('class1','class2');
> $className = $classes[$selected];
> $object = new $className;
> 
> Thanks for any help.
> 
> Thomas

I'm not sure what you'd be doing where this would be an optimal 
solution, but you can do something like this:

ushort selected = 1;
Object[] classes = [new Class1, new Class2];
Object foo = classes[selected].dup;

I believe....




More information about the Digitalmars-d mailing list