Re: Construction of classes at runtime
On Oct 9, 3:59 am, Ian Collins <ian-n...@hotmail.com> wrote:
James Kanze wrote:
On Aug 20, 11:47 am, Ian Collins <ian-n...@hotmail.com> wrote:
You can't create a class 'on the fly' from its name in C++,
you have to know the classes at compile time.
That's true for pretty much every language, isn't it. It's not
sufficient to just have a name; you need more information from
somewhere. And you can make things pretty dynamic in C++; I
have one case where I look for a dynamically linked object for
the class if it isn't already loaded.
True, but a compiled language will never match the runtime
flexibility of an interpreted one.
Yes. There are, in fact, several different levels of
flexibility possible (with, generally, more flexibility implying
less robustness). In totally dynamic languages, with fully
dynamic typing, a "struct" or a "class" is really nothing more
than an associative array; an array whose elements are indexed
by the name of the field. In such cases, you can dynamically
read a set of attribute value pairs, and use the results as a
struct. In most compiled languages, and some interpreted ones
as well, I think, the program can only deal with structs known
to it. With dynamic linking, however, it is possible to make
the set of such structs open, to add to it at runtime.
For example in PHP to process an RPC request I can write
call_user_func_array( array($object,$method), $parameters );
Where $object is the name of a class, $method is the method to
call and $parameters an array of parameters. The interpreter
will find the class, construct it and call the method. I
could write the same function in C++, but the tables of
classes and methods would have to explicitly constructed.
Or automatically generated by some other program:-). I'm not
familiar with PHP, but what you are describing doesn't sound too
different from Java's java.lang.Class.forName( "className" )
..newInstance(). As I said, I've actually implemented this once
in C++, with the programming looking for a corresponding
..so/.dll in a path if the desired class wasn't already present.
(It's interesting to note that when I did more or less the same
thing in Java, it was almost as many lines of code. Since, of
course, not just any class would do; the class had to meet
certain requirements, and I needed code to test those. In C++,
the .so/.dll wouldn't link if the class didn't meet my
Implementing total flexibility is also more or less possible;
your actual instance is basically an std::map< std::string,
boost::any >. Of course, total flexibility often results in
total chaos, but like everything else, with a good enough
process and some programmer discipline, it can be made to work.
If you really, really need it.
James Kanze (GABI Software) email:firstname.lastname@example.org
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34