Victor Bazarov wrote:
[color=blue]
>
firegun9@yahoo.com.tw wrote:[color=green]
>> After looking for the solution for a while in the group, I know this is
>> not possible in C++. So I just say my problme here.
>>
>> The input file is:
>> dev1 1 1
>> dev2 0 0 0 6
>>
>> There is a base class "Base" and two derivated classes "dev1" and
>> "dev2".
>> The best way of my code is like:
>>
>> Read_line_from_file(char* arg1, char* arg2, char* arg3);
>> Base* p_base = new arg1(arg2, arg3);
>>
>> If I could have a dynamic variable, the second statement above can new
>> any type of future derivative class without changing the codes here.
>> For example, if I have a new class dev3, I just add a line of "dev3 5 5
>> 5" into the text file, then the code will new a "dev3" object.
>> Isn't it so cool?[/color]
>
> No. If I just add a line of "screwup 13 666" into the text file, how will
> your code know what to do?
>[color=green]
>> However, I can't do that.
>> Any better idea about this?[/color]
>
> About what? So, you need to read a string and several numbers that should
> in your program lead to creation of an object of some type and pass the
> numbers to the constructor of that object. Why does the string have to be
> the same as the name of the type in your program?
>
> You need to read some beginner book on reading and parsing input files.
> Are you a subscriber of a library? Head there and look for a decent book
> on general programming. It really have nothing to do with C++, and is
> usually done the same way in all respectable languages.[/color]
He should *not* get a book on general programming because he is not wrong in
terms of general programming. He tries to do something that happens to be
not possible in C++. What he proposes is something very normal and common
in languages with reflection support.
In Java, it is good style to have settings or properties files that
determine which specific implementation of a certain interface should be
loaded. The class name to load is written into the settings file, the file
is read at runtime, and the appropriate class is loaded by the ClassLoader,
or a runtime exception is thrown (if the class does not exist).
Markus