Hello dear! Tell me please.

For example, we have some kind of class factory system. It is required that as soon as we execute include of some such class, which should be in the list of the factory, it registers itself in this factory.

those. let the factory be a static array of pointers. As soon as we execute include, the module itself creates an object and adds it to this sheet. How can I do that?

in pascale (Delphi) the module had such a wonderful section as initialization. Here you need something like an analogue. It is desirable to stat and analog, but caused when the module is disconnected (it is called, respectively, when the program ends)

Tell me please

  • include has nothing to do with modules. Modules in C ++ are completely different than in other languages ​​(Java, Python, etc.). Here it is a compilation unit and nothing else. - skegg

2 answers 2

Hm Firstly, in c ++ include it connects at compile time.

You can write code in cpp from which include is connected. This is a miracle of nature.

void RegisterInclude(char *name){ // код подключения printf("Included: %s\r\n", name); } class RegisterIncludeClass{ public: RegisterIncludeClass(char *name){ RegisterInclude(name); } }; #define RESISTER_INCLUDE(name) RegisterIncludeClass name##name(#name); 

And in the add, add:

 RESISTER_INCLUDE(имя_подключаемого_класса); 

As a result, you can save all the connected modules in the list and use as intended. The main thing is not to call the modules the same, otherwise there will be an error. I hope I understand the question correctly :).

  • I would say that the #include directive is a preprocessor directive, i.e. works before compilation as such)) - skegg

In C ++, there are separate .h files, which are specified in #include and files with the main text .cpp or .cc.

Integration classes are not classes, they can contain anything, but usually contain class declarations, maybe several in one, while class definitions are usually placed in .cpp

The very connection of these classes into the program is made by the linker, and at this stage it doesn’t matter to him what you have written in include, and the set of already compiled object files is important. One source .cpp file corresponds to one object file, the processors are not taken into account at all, they are included in the text of the .cpp file by the preprocessor.

Now at the expense of some action before the start of the main and after its (normal) completion. This is possible with the help of any external or static variables of the class type, which has a constructor and a destructor. Constructors of external variables are called before the start of main, destructors - after its completion, but in what order, if there are several of them, is unknown.