Hello. I have the following problem: there is an abstract class A, two classes are inherited from it: B and C. What should I do if it is not known at the compilation stage which class B or C will be passed to the procedure? That is, during the execution of the program, either of these two classes must be passed to the procedure, and the procedure must have exactly one parameter. How can I apply metaclasses if necessary?
1 answer
In such cases, the procedure takes class A as a parameter. For example:
type A = class end; type B = class(A) end; type C = class (A) end; ...... procedure foo(arg: A); begin .... end; .............. var b: B; c: C; begin b = B.Create(); C = C.Create(); foo(b); foo(c); end; - and there will be no abstract error from the fact that class A is abstract? - ibr
- !? It seemed to me that it was necessary to pass pointers to instances of classes. Or now paskali so clever that they already optimize such programs !? - gecube
- 2@ibr will not. You pass specific classes, not abstract ones. I advise you to read more about polymorphism and what it is eaten with. @gecube, why pass pointers ?? All objects that are declared in Delphi and so are not "real" (in the C ++ sense), but references (as in Java). When an object is passed as a parameter, a copy of the link to this object is created (which in fact differs little from the pointer passing). These principles were still in Delphi 5 (did not work with the earlier ones), and did not appear "now." - Nofate ♦
- @ibr, you don’t have to spend your respect points, just “Accept the answer” by clicking on the check mark if it helped you. - Nofate ♦
- <i> Why pass pointers? </ i> then, I'm used to C / C ++ / asm. And it surprised me a little. - gecube
|