Header and cpp or just cpp files - best practise? - c++

Looking around at different code bases I see a variety of styles:
Class "interfaces" defined in header file and the actual impl in a cpp file. In this approach the headers look well defined and easy to read but the cpp files look confusing as it's just a list of methods.
The second approach i see is just to put everything in a single class cpp file. These class files contain the definition and actual method impls in the body of the class definition. This approach looks better to me (more like Java and c#).
Which style should I be using?

For all but the simplest programs, style #2 is simply impossible. If you #include a .cpp file with function definitions from multiple other .cpp files, the definitions get added to multiple object files (.o / .obj) and the linker will complain about clashing symbols.
Use style #1 and learn to live with the confusion.

The former - interfaces in header files and class bodies in implementation files. You'll find this causes you fewer problems when working on large systems.
In C++ why have header files and cpp files?

C++ doesn't use "interfaces" they use classes - base/derived classes. I use one file to define class/and its implementation methods if the project is small and separate files if the project is large.
In java, I pack them up into one package then import it once in need.

Since you tagged with c++, go for first style. I don't find it confusing, for a Java programmer, it may seem different, but in C++, you are always going to use this approach.
In fact in my favorite IDE (MSVS), I open header file, and cpp file side by side. Makes looking up prototypes, and class declaration easy.
And when you have a dozen classes; a dozen .h files, and another dozen .cpp file, will make your work simpler. Because, when you want just to see, what a class does, you just open relevant .h file, and take a look at class members, and maybe short comments. You don't need to wade through several lines deep code.
Conclusion : The style options you gave, are option only for a small code, typically single file, with very few methods etc. Otherwise, it is not even a option. (#Thomas has given the reason why #2 is not even a option)

Header (HPP):
The header includes the declarations of your code, particularly function declarations. Technically speaking classes are defined in header-files, but again, the member functions are just declared.
Code in other files will include just this header and retain all necessary information from there.
Implementation (CPP):
The implementation includes the definition of functions, member-functions and variables.
Rationale:
Header-files gives a developer (a external user of your code) a plain overview and just offers the external available code (i.e. easy to read, only the information necessary for users).
Header-files allow the compiler to check the implementation for correctness
Header-files allow the compiler to check external code for correctness
Header-files allow for seperate-compilation. You need to keep in mind. that in former times, computers doesn't have enough resources to keep everything in main-memory during a compilation process. Header files are small, while implementation files are big.
Use #style 1, even for simple programs. So you can learn easily to work with. That maybe look outated today, especially in background of modern Multi-Pass-Compilers. But seperate header-files are even today beneficial. Rumours about the next C++-Standard appeared, as far as I know something like symbol export ( Java or C#) will be possible. But don't nail me down on this!
Notes:
- member-functions which are defined inside a class are by default inline, normally you don't want this
- use always defined guards

If you are developing large project, you'll find the first approach helps you a lot. The second approach may help you in small project. As your project becomes larger, management of complexity is a big issue of software development, and the first approach turns out to be a better choice.

What I do is:
write .cpp files, with the method names prefixed with the class name
in the .h file, create an empty class, with the appropriate name, then use a cogapp generator script, cog_addheaders.py, to insert the declarations, eg:
.cpp file: WeightsPersister.cpp
.h file: WeightsPersister.h
This way I get:
fast compilation (just needs to recompile the .cpp file, unless I change the class interface)
few issues with circular declarations
acceptably low tedious mindless manual work :-)

Related

How to properly declare functions in C++? [duplicate]

I know this maybe quite subjective, but are there any general rules for situations when it is not necessary for code to be split into two files?
For example is the class is extremely small, or if the file simply holds some global definitions or static functions? Also, in these cases, should the single file be a .cpp file or a .h file?
On the technical side, whenever you need to obey the one definition rule you have to separate declarations from definitions, since you will need to include the declarations many times in multiple translation units, but you must only provide one single definition.
In aesthetic terms, the answer could be something like "always", or "systematically". In any case, you should always have a header for every logical unit of code (e.g. one class or one collection of functions); and the source file is one that is possibly optional, depending on whether or not you have everything defined inline (exempting you from ODR), or if you have a template library.
As a meta strategy, you should seek to decouple the compilation units as much as possible, so that you can include only what's needed in a fine-grained way. This allows your project to grow without having compilation times become unbearable, and it makes it much easier to reuse code in other projects.
I favor putting code in .hpp files but am very often compelled to put the implementation in the .cpp for any of the following reasons:
Reducing build time. This is the #1 reason to use .cpp files... and the reason most code you find in .hpp files is small and simple. When the implementation changes, you don't want to have to rebuild every .cpp that includes it.
When the function's linkage is important. For example, if the function is exported as a library (e.g. DLL) function, it's important that it select a single compilation unit to live in. Or for static / global instances. This is also important for distributing an import header for a DLL.
When you wish to hide implementation details when distributing a library
The definition and declaration are not identical. This can be the case with respect to constness of arguments.
You want a "clean" overview of the interface in the .hpp file. I find that with modern code tools and increasing familiarity with single-code-file languages like javascript / C# / inline C++, this is not a strong argument.
You explicitly do not want the function to be declared inline. Although, it won't matter; the optimizing compiler will likely inline if it wants to.
There are logical motivations for keeping code inline in a .hpp file:
Why have two files when you can have one?
Duplicating the declaration / function headers is unnecessary maintenance and feels redundant. We have code analysis tools to show interfaces.
The concept that inline / template code must be put in a header and other code is put in a .cpp is arbitrary. If we are forced to put inline code in a .hpp file, and this is OK, then why not put all code in a .hpp file?
I am pretty sure though that the tradition of separate .cpp and .hpp files is far stronger than the reasoning however.
I know this maybe quite subjective, but are there any general rules
for situations when it is not necessary for code to be split into two
files?
Split the code into header and source whenever you can.
Generally, this shouldn't be done in next cases :
the code consists of template classes and functions (unless you
explicitly instantiate templates in the source file)
the header consists only of inline functions
should the single file be a .cpp file or a .h file?
Should be the header file (.h).
The rule I use is the following:
Whenever you can put code into a cpp file, do it.
The reasons are multiple:
Header files serve as rudimentary documentation. It is better not to clutter them with code.
You can also use pimpls at some places if you feel like, for the reason above.
It reduces compilation times:
whenever you change a .cpp, only this file will be recompiled.
whenever a header is included, it only contains the minimal amount of code needed
It allows you to assess more easily which part of your code depends on which other part, just by looking at which headers are included. This point mandates another rule of mine:
Whenever you can forward declare a class instead of including a header, do it.
This way, the .cpp files carry the dependency information between parts of your source. It also lowers build times.
I know this maybe quite subjective, but are there any general rules for situations when it is not necessary for code to be split into two files?
It's not always subjective; you will very good reasons to separate them in large projects. It's good to get into the practice of separating them, and learning when it is and is not appropriate to separate definition from declaration. It's hard to answer your question without knowing how complex your codebase will become.
For example is the class is extremely small
It's still not necessarily a bad idea to separate them, in general.
or if the file simply holds some global definitions
The header should not contain global definitions which require static construction, unless necessary.
or static functions?
These do not belong anywhere in C++. Use inline, or anonymous namespace. If you mean within a class' body, "it depends on the instruction count, if you are hoping it will be inlined".
Also, in these cases, should the single file be a .cpp file or a .h file?
The single file should be a header. Rationale: You should not #include cpp files.
And don't forget that intermodule (aka link-time) optimizations are getting better and better.
C++ compilation times are long, and it's very very very time consuming to fix this after the fact. I recommend that you get into the practice of using cpp files before your build times and dependencies explode.

Is it always a good idea to create .h and .cpp files together? [duplicate]

I've never really understood why C++ needs a separate header file with the same functions as in the .cpp file. It makes creating classes and refactoring them very difficult, and it adds unnecessary files to the project. And then there is the problem with having to include header files, but having to explicitly check if it has already been included.
C++ was ratified in 1998, so why is it designed this way? What advantages does having a separate header file have?
Follow up question:
How does the compiler find the .cpp file with the code in it, when all I include is the .h file? Does it assume that the .cpp file has the same name as the .h file, or does it actually look through all the files in the directory tree?
Some people consider header files an advantage:
It is claimed that it enables/enforces/allows separation of interface and implementation -- but usually, this is not the case. Header files are full of implementation details (for example member variables of a class have to be specified in the header, even though they're not part of the public interface), and functions can, and often are, defined inline in the class declaration in the header, again destroying this separation.
It is sometimes said to improve compile-time because each translation unit can be processed independently. And yet C++ is probably the slowest language in existence when it comes to compile-times. A part of the reason is the many many repeated inclusions of the same header. A large number of headers are included by multiple translation units, requiring them to be parsed multiple times.
Ultimately, the header system is an artifact from the 70's when C was designed. Back then, computers had very little memory, and keeping the entire module in memory just wasn't an option. A compiler had to start reading the file at the top, and then proceed linearly through the source code. The header mechanism enables this. The compiler doesn't have to consider other translation units, it just has to read the code from top to bottom.
And C++ retained this system for backwards compatibility.
Today, it makes no sense. It is inefficient, error-prone and overcomplicated. There are far better ways to separate interface and implementation, if that was the goal.
However, one of the proposals for C++0x was to add a proper module system, allowing code to be compiled similar to .NET or Java, into larger modules, all in one go and without headers. This proposal didn't make the cut in C++0x, but I believe it's still in the "we'd love to do this later" category. Perhaps in a TR2 or similar.
You seem to be asking about separating definitions from declarations, although there are other uses for header files.
The answer is that C++ doesn't "need" this. If you mark everything inline (which is automatic anyway for member functions defined in a class definition), then there is no need for the separation. You can just define everything in the header files.
The reasons you might want to separate are:
To improve build times.
To link against code without having the source for the definitions.
To avoid marking everything "inline".
If your more general question is, "why isn't C++ identical to Java?", then I have to ask, "why are you writing C++ instead of Java?" ;-p
More seriously, though, the reason is that the C++ compiler can't just reach into another translation unit and figure out how to use its symbols, in the way that javac can and does. The header file is needed to declare to the compiler what it can expect to be available at link time.
So #include is a straight textual substitution. If you define everything in header files, the preprocessor ends up creating an enormous copy and paste of every source file in your project, and feeding that into the compiler. The fact that the C++ standard was ratified in 1998 has nothing to do with this, it's the fact that the compilation environment for C++ is based so closely on that of C.
Converting my comments to answer your follow-up question:
How does the compiler find the .cpp file with the code in it
It doesn't, at least not at the time it compiles the code that used the header file. The functions you're linking against don't even need to have been written yet, never mind the compiler knowing what .cpp file they'll be in. Everything the calling code needs to know at compile time is expressed in the function declaration. At link time you will provide a list of .o files, or static or dynamic libraries, and the header in effect is a promise that the definitions of the functions will be in there somewhere.
C++ does it that way because C did it that way, so the real question is why did C do it that way? Wikipedia speaks a little to this.
Newer compiled languages (such as
Java, C#) do not use forward
declarations; identifiers are
recognized automatically from source
files and read directly from dynamic
library symbols. This means header
files are not needed.
To my (limited - I'm not a C developer normally) understanding, this is rooted in C. Remember that C does not know what classes or namespaces are, it's just one long program. Also, functions have to be declared before you use them.
For example, the following should give a compiler error:
void SomeFunction() {
SomeOtherFunction();
}
void SomeOtherFunction() {
printf("What?");
}
The error should be that "SomeOtherFunction is not declared" because you call it before it's declaration. One way of fixing this is by moving SomeOtherFunction above SomeFunction. Another approach is to declare the functions signature first:
void SomeOtherFunction();
void SomeFunction() {
SomeOtherFunction();
}
void SomeOtherFunction() {
printf("What?");
}
This lets the compiler know: Look somewhere in the code, there is a function called SomeOtherFunction that returns void and does not take any parameters. So if you encouter code that tries to call SomeOtherFunction, do not panic and instead go looking for it.
Now, imagine you have SomeFunction and SomeOtherFunction in two different .c files. You then have to #include "SomeOther.c" in Some.c. Now, add some "private" functions to SomeOther.c. As C does not know private functions, that function would be available in Some.c as well.
This is where .h Files come in: They specify all the functions (and variables) that you want to 'Export' from a .c file that can be accessed in other .c files. That way, you gain something like a Public/Private scope. Also, you can give this .h file to other people without having to share your source code - .h files work against compiled .lib files as well.
So the main reason is really for convenience, for source code protection and to have a bit of decoupling between the parts of your application.
That was C though. C++ introduced Classes and private/public modifiers, so while you could still ask if they are needed, C++ AFAIK still requires declaration of functions before using them. Also, many C++ Developers are or were C devleopers as well and took over their concepts and habits to C++ - why change what isn't broken?
First advantage: If you don't have header files, you would have to include source files in other source files. This would cause the including files to be compiled again when the included file changes.
Second advantage: It allows sharing the interfaces without sharing the code between different units (different developers, teams, companies etc..)
The need for header files results from the limitations that the compiler has for knowing about the type information for functions and or variables in other modules. The compiled program or library does not include the type information required by the compiler to bind to any objects defined in other compilation units.
In order to compensate for this limitation, C and C++ allow for declarations and these declarations can be included into modules that use them with the help of the preprocessor's #include directive.
Languages like Java or C# on the other hand include the information necessary for binding in the compiler's output (class-file or assembly). Hence, there is no longer a need for maintaining standalone declarations to be included by clients of a module.
The reason for the binding information not being included in the compiler output is simple: it is not needed at runtime (any type checking occurs at compile time). It would just waste space. Remember that C/C++ come from a time where the size of an executable or library did matter quite a bit.
Well, C++ was ratified in 1998, but it had been in use for a lot longer than that, and the ratification was primarily setting down current usage rather than imposing structure. And since C++ was based on C, and C has header files, C++ has them too.
The main reason for header files is to enable separate compilation of files, and minimize dependencies.
Say I have foo.cpp, and I want to use code from the bar.h/bar.cpp files.
I can #include "bar.h" in foo.cpp, and then program and compile foo.cpp even if bar.cpp doesn't exist. The header file acts as a promise to the compiler that the classes/functions in bar.h will exist at run-time, and it has everything it needs to know already.
Of course, if the functions in bar.h don't have bodies when I try to link my program, then it won't link and I'll get an error.
A side-effect is that you can give users a header file without revealing your source code.
Another is that if you change the implementation of your code in the *.cpp file, but do not change the header at all, you only need to compile the *.cpp file instead of everything that uses it. Of course, if you put a lot of implementation into the header file, then this becomes less useful.
C++ was designed to add modern programming language features to the C infrastructure, without unnecessarily changing anything about C that wasn't specifically about the language itself.
Yes, at this point (10 years after the first C++ standard and 20 years after it began seriously growing in usage) it is easy to ask why doesn't it have a proper module system. Obviously any new language being designed today would not work like C++. But that isn't the point of C++.
The point of C++ is to be evolutionary, a smooth continuation of existing practise, only adding new capabilities without (too often) breaking things that work adequately for its user community.
This means that it makes some things harder (especially for people starting a new project), and some things easier (especially for those maintaining existing code) than other languages would do.
So rather than expecting C++ to turn into C# (which would be pointless as we already have C#), why not just pick the right tool for the job? Myself, I endeavour to write significant chunks of new functionality in a modern language (I happen to use C#), and I have a large amount of existing C++ that I am keeping in C++ because there would be no real value in re-writing it all. They integrate very nicely anyway, so it's largely painless.
It doesn't need a separate header file with the same functions as in main. It only needs it if you develop an application using multiple code files and if you use a function that was not previously declared.
It's really a scope problem.
C++ was ratified in 1998, so why is it designed this way? What advantages does having a separate header file have?
Actually header files become very useful when examining programs for the first time, checking out header files(using only a text editor) gives you an overview of the architecture of the program, unlike other languages where you have to use sophisticated tools to view classes and their member functions.
If you want the compiler to find out symbols defined in other files automatically, you need to force programmer to put those files in predefined locations (like Java packages structure determines folders structure of the project). I prefer header files. Also you would need either sources of libraries you use or some uniform way to put information needed by compiler in binaries.
I think the real (historical) reason behind header files was making like easier for compiler developers... but then, header files do give advantages.
Check this previous post for more discussions...
Well, you can perfectly develop C++ without header files. In fact some libraries that intensively use templates does not use the header/code files paradigm (see boost). But In C/C++ you can not use something that is not declared. One practical way to
deal with that is to use header files. Plus, you gain the advantage of sharing interface whithout sharing code/implementation. And I think it was not envisionned by the C creators : When you use shared header files you have to use the famous :
#ifndef MY_HEADER_SWEET_GUARDIAN
#define MY_HEADER_SWEET_GUARDIAN
// [...]
// my header
// [...]
#endif // MY_HEADER_SWEET_GUARDIAN
that is not really a language feature but a practical way to deal with multiple inclusion.
So, I think that when C was created, the problems with forward declaration was underestimated and now when using a high level language like C++ we have to deal with this sort of things.
Another burden for us poor C++ users ...

C++: including a class definition in a header file

A number of posts are pretty adamant that source code should not go in a header and that header files should be kept to a minimum. I've been sticking to this with my own code, but I want to use someone else's code to achieve a particular goal (the code is documented here http://ftp.arl.mil/random/).
I notice that this is basically one giant header file which defines a class. Is it OK to leave this in a header file? Should I copy it all to a .cpp file and create a new .h that just declares the functions, structures etc?
If I split it into a .cpp and a .h as I propose, will it work? Or do classes need to be in the header to be accessed by all source code?
Declarations (stating that something exists) that need to be seen in more than one cpp file should go in header files. Declarations that are local to a single cpp file should be in the cpp file itself.
Definitions (providing the body of a function or allocating/initializing variables) should usually go in cpp files, but not always.
The question you need to understand is does the compiler have enough information to do its job if it has seen the header file and not the corresponding cpp file.
For example: you can call a method if the compiler has seen the declaration (the method prototype) -- unless the method is generic (a templated method or a member of a templated class) or inline in which case the compiler needs to have seen the definition (the method body) too.
Therefore normal methods go in cpp files; templated methods go in header files; inline methods go in header files (and so on).
There are other situations in which definitions belong in header files including static member constants. It all comes back to giving the compiler the information it needs one one hand vs minimizing coupling between separate compilable units on the other. Again there are no hard-and-fast rules, just guidelines coupled with the knowledge and experience of the developer writing the code.
.h files are usually shared between many .cpp files.
The global variables and function code should not be in the header files, because it would make duplicates during linking.
Constants, defines, function headers and class declarations are fine in header files. You don't have to declare the same thing multiple times and you can share the definitions between .cpp files.
source code should not go in a header and that header files should be
kept to a minimum.
This is a popular assertion, and while it may generally not be bad advice, you should not draw absolute conclusions from it. Sometimes headers should be minimal and not include definitions. Sometimes the opposite is true. There are reasons why you would do one or the other, but "people say" is not one of them.
Consider the C++ Standard Library. Better yet, consider Boost. Some prestigious C++ experts have said that Boost is the most well-designed C++ library in history. But if you look at the libraries you'll see that they are basically just giant header files for the most part. How does this reconcile with what "they" say?
The point is this: you must understand the reasons why certain files are designed the way they are, and make up your own mind about what is Right and Wrong for each situation.
Should I copy it all to a .cpp file and create a new .h that just
declares the functions, structures etc?
I would say probably not. This sounds like a recipe for a maintenance nightmare to me. It would be my first instinct to use the 3rd party library they way the library's author intended it to be used. That way you won't be off the support grid, and you won't introduce a new set of complications that you will be completely on your own to figure out. Unless you have a specific, provable reason to alter the architecture of the library, don't. "They say" isn't a good enough reason for me.

When should I not split my code into header and source files?

I know this maybe quite subjective, but are there any general rules for situations when it is not necessary for code to be split into two files?
For example is the class is extremely small, or if the file simply holds some global definitions or static functions? Also, in these cases, should the single file be a .cpp file or a .h file?
On the technical side, whenever you need to obey the one definition rule you have to separate declarations from definitions, since you will need to include the declarations many times in multiple translation units, but you must only provide one single definition.
In aesthetic terms, the answer could be something like "always", or "systematically". In any case, you should always have a header for every logical unit of code (e.g. one class or one collection of functions); and the source file is one that is possibly optional, depending on whether or not you have everything defined inline (exempting you from ODR), or if you have a template library.
As a meta strategy, you should seek to decouple the compilation units as much as possible, so that you can include only what's needed in a fine-grained way. This allows your project to grow without having compilation times become unbearable, and it makes it much easier to reuse code in other projects.
I favor putting code in .hpp files but am very often compelled to put the implementation in the .cpp for any of the following reasons:
Reducing build time. This is the #1 reason to use .cpp files... and the reason most code you find in .hpp files is small and simple. When the implementation changes, you don't want to have to rebuild every .cpp that includes it.
When the function's linkage is important. For example, if the function is exported as a library (e.g. DLL) function, it's important that it select a single compilation unit to live in. Or for static / global instances. This is also important for distributing an import header for a DLL.
When you wish to hide implementation details when distributing a library
The definition and declaration are not identical. This can be the case with respect to constness of arguments.
You want a "clean" overview of the interface in the .hpp file. I find that with modern code tools and increasing familiarity with single-code-file languages like javascript / C# / inline C++, this is not a strong argument.
You explicitly do not want the function to be declared inline. Although, it won't matter; the optimizing compiler will likely inline if it wants to.
There are logical motivations for keeping code inline in a .hpp file:
Why have two files when you can have one?
Duplicating the declaration / function headers is unnecessary maintenance and feels redundant. We have code analysis tools to show interfaces.
The concept that inline / template code must be put in a header and other code is put in a .cpp is arbitrary. If we are forced to put inline code in a .hpp file, and this is OK, then why not put all code in a .hpp file?
I am pretty sure though that the tradition of separate .cpp and .hpp files is far stronger than the reasoning however.
I know this maybe quite subjective, but are there any general rules
for situations when it is not necessary for code to be split into two
files?
Split the code into header and source whenever you can.
Generally, this shouldn't be done in next cases :
the code consists of template classes and functions (unless you
explicitly instantiate templates in the source file)
the header consists only of inline functions
should the single file be a .cpp file or a .h file?
Should be the header file (.h).
The rule I use is the following:
Whenever you can put code into a cpp file, do it.
The reasons are multiple:
Header files serve as rudimentary documentation. It is better not to clutter them with code.
You can also use pimpls at some places if you feel like, for the reason above.
It reduces compilation times:
whenever you change a .cpp, only this file will be recompiled.
whenever a header is included, it only contains the minimal amount of code needed
It allows you to assess more easily which part of your code depends on which other part, just by looking at which headers are included. This point mandates another rule of mine:
Whenever you can forward declare a class instead of including a header, do it.
This way, the .cpp files carry the dependency information between parts of your source. It also lowers build times.
I know this maybe quite subjective, but are there any general rules for situations when it is not necessary for code to be split into two files?
It's not always subjective; you will very good reasons to separate them in large projects. It's good to get into the practice of separating them, and learning when it is and is not appropriate to separate definition from declaration. It's hard to answer your question without knowing how complex your codebase will become.
For example is the class is extremely small
It's still not necessarily a bad idea to separate them, in general.
or if the file simply holds some global definitions
The header should not contain global definitions which require static construction, unless necessary.
or static functions?
These do not belong anywhere in C++. Use inline, or anonymous namespace. If you mean within a class' body, "it depends on the instruction count, if you are hoping it will be inlined".
Also, in these cases, should the single file be a .cpp file or a .h file?
The single file should be a header. Rationale: You should not #include cpp files.
And don't forget that intermodule (aka link-time) optimizations are getting better and better.
C++ compilation times are long, and it's very very very time consuming to fix this after the fact. I recommend that you get into the practice of using cpp files before your build times and dependencies explode.

Using C++ headers (.h) vs headers plus implementation (.h + .cpp), what are the disadvantages?

As a novice C++ programmer I have always put my classes interface in .h files and implementation in .cpp files. However I have recently tried C# for a while and I really like its clean syntax and way to organize files, in particular there is no dinstinction between headers and implementation, you usually implement a class for each .cs file and you don't need headers.
I know that in C++ this is also possible (you can code "inline" functions in .h files), but up to now I have always seen a clear distinction between .h and .cpp files in C++ projects. What are the advantages and disadvantages of this approach?
Thank you
There's a few ways that separating the two help in C++. Firstly, if you'd like to update a library without changing an interface then having the code in the C++ file means that you simply can update the library rather than the library plus the headers. Secondly it hides the implementation. That is, it forces people to look at your class only in terms of the interface, the thing that should concern them if the code is well written. Finally, there's a sort of asthetic cleanness with interface + documentation that comes with this separation. It's something you have to get used to but after a while it'll feel natural (opinion.)
Don't forget build times.
Putting implementation code in header files makes them more likely to be changed. And changing header files will cause rebuilds of all the CPP files that include them, which in turn increases build times. This can be significant in larger projects.
I am also a fan of keeping the implementation hidden from users of my libraries. Unfortunately this doesn't work for template classes.
My rule of thumb: keep declarations in .H files, keep definitions in .CPP files.
it's cooler to have the symbols defined at one place for the case you wanted to compound C++ with already compiled binaries (typicly when using a library). imagine you need to define external symbols for global stuff in your binaries. if you had .cpp and .h code in the same file you would have to define the symbols for your binaries for every such file. in two files way you could have just the one .h with definitions for binaries and a lot of .cpp files that use it.
The main difference is that something implemented inside a .h file will be placed in every compilation unit that includes that header, this will create redundancy during the compile phase in the final binary executable.. while splitting with .h and .cpp will compile it in a single object file that is later linked against the other objects files by having just one compiled binary code that implements that header file.
In addition if you declare things just inside a .h you are not able to share variables and structures between more other .cpp files..
It's interesting to note that C# seems to be going in the C/C++ direction to some extent recently, with the introduction of partial classes.
The particular advantage of this in the IDE is that the Visual Studio designer will modify the part of the class that deals with visual controls, or data members, and their layout without any worries about mucking up the methods (application logic) that reside in a separate file.
I would echo #wheaties and add a few further items
Compilation is easier (may be it's just me), I've never been able to get compilation to work just right if you modify the header only (as in all the implementation files that have included it). I believe in Makefiles you have to add the dependencies manually which is a real pain in very large scale projects (again could just be me). So if you have your code in implementation files, then changes simply mean recompiling that particular file - very useful when you want to do quick changes, build and test.
Let me re-iterate the hiding aspect, most often you don't want people to know the implementation details due to the sensitive nature of the code, and thus only expose the headers plus the pre-built libraries, and the separation is key here.
Forward declarations, neat trick where you don't need to include the implementation details of a class in the header file if it's not being "used" in any of the code in the header, but then in the implementation file you can include the real header and "it all works nicely" (helps if you have cyclic dependencies - why you have them is different issue!)
On a recent large project the authors of systems I wanted to use had placed a lot of the code in .h files. When including their .h files into my own source it added further dependencies to my file. After including the dependencies for their project I ended up with typedef collisions. If they had separated the code and only placed declarations in the .h file it would have been much simpler. I suggest using posix types and only putting declarations into .h files.
I see that a lot of responses advocate separation, primarily for build-time and implementation hiding benefits. Both are definitely pluses, though I'll argue the counter example: Boost.
Most Boost libraries use a .hpp file with no external linking. The reason is that this is often required in the case of templates, when the compiler must know the argument types from the calling routine. So you might not have a choice if you want to stick with the "modern" C++ approach of shunning classes for templates.
As for the comparison part of .cs versus .cpp/.h I think you need to keep in mind the background the lead architect of C#: Anders Hejlsberg. In Delphi you also don't have the distinction of header and module (ignoring include files for this discussion). You simply have two sections in a unit file initialization and implementation.
The other points were already mentioned.