Is there a good way to avoid duplicating prototype methods in C ++?

Most C ++ class method signatures are duplicated between the declaration, usually in the header files, and the definition in the source files of the code I read. I find this repetition undesirable, and code written this way suffers from poor link locality. For example, methods in the source files often refer to instance variables declared in the header file; you must constantly switch between header files and source files when reading code.

Can anyone recommend a way to avoid this? Or am I mostly going to confuse experienced C ++ programmers without doing something in the usual way?

See also Question 538255 C ++ code in header files , where someone is told that everything should go in the header.

+3
source share
5 answers

There is an alternative, but treatment is worse than disease; define all function bodies in the header or even built into the class, for example, C #. The downside is that it will significantly increase compilation time, and it will annoy C ++ programmers. It can also lead you to some annoying circular addiction situations that, although solvable, are unpleasant to solve.

Personally, I just set my IDE to have a vertical split, and put the header file on the right side and the source file on the left.

+9

, - ?

Java/Python/etc. , . , , inline ( ). , - .

++, Ada , , - - , , . , . , TDD, stubbing .

+6

. , , . , . C/++ - .

+4

++ , , . , , . , . , , , (.. ), .

+3

" ". , , . CPP , . . , , . , "", CPP .

InterfaceClass* InterfaceClass::Create()
{
     return new ImplementationClass;
}

Thus, you effectively hide the implementation from any external user. However, you cannot create a class on the stack only on the heap ... but it really solves your problem AND provides a better level of abstraction. In the end, though, if you are not ready to do this, you need to stick to what you are doing.

0
source

Source: https://habr.com/ru/post/1721486/


All Articles