Misconception. A class in C++ does not need to have its own *.cpp
file and there are pragmatical reasons to avoid having lots of tiny *.cpp
files (and prefer instead having less *.cpp
files, each defining several related classes and functions, so being slightly bigger).
A given translation unit (e.g. the *.cpp
files and all the header files it is #include
-ing) can (and usually does) define and declare several class
-es and functions.
In practice, you code in C++ by using several standard containers or other standard C++ facilities provided by standard C++ headers, such as smart pointers from <memory>
, strings from <string>
, vectors from <vector>
, sorting functions from <algorithm>
and so on. The powerful C++ standard library is one of the reasons to code in C++ (instead of C, for instance). So you would #include
perhaps several standard headers like <vector>
or <map>
. Standard headers are quite complex: on my Linux machine, #include <vector>
generally expands to more than ten thousand of included lines (and that is one of the reasons why C++ code compiles slowly). So it is unwise (but possible) to have many small C++ files of a hundred lines each which are including some standard header, because a small yourcode.cpp
file containing #include <vector>
and two hundreds lines of your C++ code is expanded to much more: the compiler parses about 10000 lines of code (LOC) from <vector>
and 200LOC of your code, so 10200 LOC in total.
BTW, you can ask your compiler to give the preprocessed form of your translation unit (with GCC, using g++ -C -E yourcode.cpp > yourcode.ii
) and look (with an editor or a pager) inside that yourcode.ii
.
(your example is not genuine C++11 code; in practice, it should often use standard containers and some other features -smart pointers, threads, standard algorithms...- of the rich C++ standard library, but it does not)
So I recommend to have your *.cpp
containing at least a thousand or two of your C++ source code lines, and of course they could define several of your related classes (and functions). In some cases, a single C++ class
might be implemented in several C++ files (because that class has a lot of methods).
BTW, in your C++ classes, a lot of small functions (including member functions) are inlined and you'll define them in some of your header file.
I recommend studying the source code of several C++ free software projects for inspiration. You'll find many of them on github or elsewhere.