This question is not intended to be a repeat of "Why should I not include cpp files and instead use a header?" and is more of a question of practices.
To best frame this question let me explain. When writing a class it can grow quickly to over a few hundred lines if not more. For readability purposes I would like to break a class into individual files on a per method basis. To be clear I am not suggesting making the entire project into a set of includes for reasons mentioned in the post listed above, but rather break a class into components contained in their own files.
The following snippets of code is an illustration of what I mean
main.cpp
#include <iostream>
#include "helloClass.h"
using namespace std;
int main()
{
hello a;
cout<<a.out();
cin.get();//just to pause execution
}
helloClass.h
#ifndef HELLOCLASS_H
#define HELLOCLASS_H
#include <string>
class hello
{
std::string message;
public:
std::string out();
hello();
};
#endif
helloClassMain.cpp
#include "helloClass.h"
using namespace std;
hello::hello()
{
message = "Hello World!";
};
#include "helloClassOut.cpp"
helloClassOut.cpp
string hello::out()
{
return message;
}
This will compile fine and execute as expected. I find an added benefit when there happens to be an error because the compiler will not only tell you what line but also the file that the error is in. For example I compiled it with a undeclared variable
$ c++ main.cpp helloClassMain.cpp -o hello
In file included from helloClassMain.cpp:8:0:
helloClassOut.cpp: In member function ‘std::string hello::out()’:
helloClassOut.cpp:3:1: error: ‘fail’ was not declared in this scope
fail="test";
I find this helpful to say the least and it allows me to think of the file helloClassMain.cpp as the entry point for the hello class and all of it's methods and attributes.
I understand that this is in the end the same thing as having the class written out in the same file because of how a compiler works. It is just a matter of being able to easier read, troubleshoot, etc.
Finally the questions.
- Is this bad practice?
- Would it make hell for those who are collaborating with me on a project?
- Is there a core concept that I am missing here? I am sure I am not the first to consider this solution.
- Have I asked a question more about preference and not so much best practices?
- Finally is there a name for what I am describing other than bad?