The Cool Giraffe wrote:
Please note that i do intend to use a header file. However,
i'm not sure if it's really needed or just a convention.
Suppose we have the following two files.
// Something.h
class Something {
private: int number;
public:
Something ();
~Something ();
void doSome ();
};
// Something.cpp
#include "Something.h"
int number;
Something::Something () {this.number = 10;}
Something::~Something () {}
void Something::doSome () {this.number = 5;}
Can one turn that into one, single CPP-file? How?
First point
'int number;' in Something.cpp is unnecessary. It's a completely
different thing from the number in the Something class. Get rid of int
number form Something.cpp.
Main point
There are two kinds of 'thing' in C++, those that can be compiled only
once and those that can be compiled multiple times in one program. When
you put (say) a class definiton in a header and then include that header
file in two cpp files you are compiling that class definition twice
within the same program. This is OK because class definitions are one of
the things that you can compile several times in one program.
An example of something that you cannot compile multiple times in one
program is a non-inline function definition. If you tried to put a
non-inline function definition in a header file and included that header
file in two seperate cpp file you would get some sort of multiple
definition error.
Inline functions are different, they can be compiled multiple times and
that is why it is OK to put them in a header file. In fact no matter
what any might tell you different, that is the meaning of 'inline' in
C++. It allows you to compile a function multiple times.
Now the C++ standard only talks about what can be compiled once and what
can be compiled multiple times. It's only a convention that we group all
the thing that can be compiled multiple times together and put them into
something we call a header file, and that we put all the things that can
only be compiled once only into something we call a cpp file. And then
to make sure that the stuff in a cpp file doesn't get compiled multiple
times we have a couple more conventions, 'compile all the cpp files
individually ', and 'don't include one cpp file in another'.
Now to answer your question, if you where to put all that code into
Something.cpp, the only way any other code could access the class
definition would be to include Something.cpp. Because you code includes
things which can be compiled only once (the non-inline constructor,
destructor and doSome methods) that would only work provided it was done
only once (and provided you didn't compile Something.cpp idependently).
If you really want only one file, then the correct way would be to make
the whole thing a header file, my making all the constructors etc. inline.
Hope this answers your question.
john