Reputation: 1145
I know template definition and its implementation can and has to put together, but how about (non-template) class?
Personally speaking I prefer put class and its implementation together if possible, since it's simplier to use, you only need to include the header file in your project, don't need to bother with the implementation files.
Upvotes: 0
Views: 193
Reputation: 19032
Short answer, yes.
The longer answer, is also yes, but there are valid reasons to not want to do that. As the size (and complexity) of a project grows, a simple change to an implementation detail of a class that is used in a lot of places (say, changing of a log message or something seemingly benign), now means that all files in the project that include that file directory (or indirectly) need to be recompiled. This can significantly increase your build times.
Upvotes: 3
Reputation: 208323
It can be done, but you would force all users of your class to recompile every time you change the implementation, and recompiling will also be slower. For that you need the function definitions to be inline
.
// in header
struct T {
void f() { std::cout << "f()\n"; }
void g();
};
inline void T::g() {
std::cout << "g()\n";
}
Now the problem comes if your class has static member variables, as those need to be defined in exactly one translation units. For that you will still need to provide a .cpp.
In any case I would advise against following this approach. When in Rome do as the romans do, and that in C and C++ means separate compilation and division of headers and implementation files.
Upvotes: 5