It seems to me a bit wild, inconvenient, and complicating the readability of the code is the need to specify the имя_класса before each function in the class implementation file.

A.hpp file:

 class A { int func(int par); } 

A.cpp file:

 int A::func(int par){ return par*2/4+1; } 

To pack the implementation of functions in a class, you can write code in the headers (you get ala in Java ). It also says why it's not cool.

 class A { int func(int par){ return 2; }; } 

Maybe you know other options for writing and organizing code?

  • I do not see any reduction in readability from what I write to AES :: DecryptBlock and will know exactly what it is about. But DecryptBlock is unclear what class (out of a couple of dozen) exactly readability reduces. - Vladimir Martyanov
  • one
    Yah? The readability does not complicate it precisely, since it is possible to immediately determine which class methods are implemented. In ++ there is no agreement that cpp implements strictly methods from hpp of the same name, that is, it is possible to implement methods of all classes in one Wed (and they can be repeated by name) - therefore, to distinguish them, it’s done like this and in another way you don’t write only if everything is in the header file. - Alexey Sarovsky

1 answer 1

This is a problem / feature of the C ++ compilation model.

The fact is that C ++ compiles only .cpp files, and each of them is independent . This means that when compiling it does not know what this text refers to, it does not know the context. When C ++ sees file methods, the compiler has now scanned hundreds (this is not an exaggeration!) Of headers and saw preliminary descriptions of hundreds of classes. He cannot just figure out which method this method applies to.

Even if another method of organizing compilation can be devised (for example, using a preprocessor somehow), the method you described is the usual and practically the only generally accepted method of organizing source code in C ++. Therefore, any other organization of the code is likely to cause confusion among your colleagues.

In other languages, for example, C #, there is no such peculiarity, because all functions are defined inside the class. There are no problems with compilation, as in the question you specified, because #include (which is essentially a simple textual substitution) is not used to find other classes, but a two-pass and indivisible compilation: the compiler does not “forget” "What he saw in other files.

In others, for example, Javascript, the problem is even wider, because the methods of an object class can be defined anywhere and “appear” in an object at any stage of its life cycle.