I'm starting to work with C++ and I come from C and Java. I know that in C is strongly advisable to write variable/types/function declarations in the header and variable/types/function definitions in the source code; so when I started coding in C++ I thought to adhere to the same convention as well.
Unluckly for me, in C++ there are several exceptions to this rule, among the others:
- template classes;
- inline functions;
- constexpr functions;
This lead me to some confusion in the files: most of them are headers with *.cpp
files containing few medium/big member functions.
So my question is: assuming to code only with classes, not with plain C, why can't I just put everything in the header and have no cpp files? (sort of Java style); to clarify: I will mostly have to deal with classes, template classes, at most template functions.
For example in Foo.hpp
:
class Foo {
public:
foo() {
//body
}
bar() {
//body
}
}
instead of having the division between *.hpp
and *.cpp
:
//file Foo.hpp
class Foo {
public:
foo();
bar();
}
//file Foo.cpp
Foo::foo() {
//body
}
Foo::bar() {
//body
}
Of course something like static global variables will be put in .*cpp
, but for my understanding they are the only thing that is required to be put in cpps (and their use is strongly discouraged as well).
Can you please tell me what are the weaknesses of this approach? Being a beginner in C++ I'm sure to have ignore some important factor. In my naive view, there is nothing that requires to be in the cpp files (assuming that I'm coding only with classes of course).
Thanks