First Steps: Dynamic class instantiation

Kirk McDonald kirklin.mcdonald at gmail.com
Sat Jan 27 20:14:06 PST 2007


Thomas wrote:
> 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.
> 

This can't really be done in D, which is statically typed. Languages 
like PHP are dynamically typed. You'll have to do some re-thinking of 
your design, I think.

First, you'll want all of your classes to either derive from the same 
class or implement the same interface. Let's call this base class (or 
interface) Base.

You could try something like this:

int selected = 1;
Base object;

switch (selected) {
     case 1:
         object = new Class1;
         break;
     case 2:
         object = new Class2;
         break;
     // and so on
}

You might also consider using an enum instead of an int for selected.

-- 
Kirk McDonald
Pyd: Wrapping Python with D
http://pyd.dsource.org



More information about the Digitalmars-d mailing list