Related
I declare all variables and functions in .h file and has become my habit to do that (I'm programming with cocos2dx)
And I read that you should try to include the least in .h file and the most in .cpp file.
Because I declare all variables and functions in .h file, If I need to use another class from another file, then I need to include that class in the .h file to declare that class as a variable.
So I want to know the importance of declaring variables in .h file and .cpp file. I want to know which way is most standard as well.
If there is no difference, then why people would declare variables and functions in private file because declaring a function in .h file requires you to write it again in .cpp file.
ie)
.h file:
class classA {
private:
void function();
};
.cpp file:
void classA::function() {
...do something...
}
What is the importance of declaring variables and functions in header files?
Declare anything that is needed outside of the code in the .cpp file in the header file, and no more. Try to minimise the amount in there as much as possible. The reason for this is that other programmers could be looking at your header (.h) file, it is essentially their API. As an OOP programmer you want to hide as much of the internal workings of your objects as possible i.e. you do not want people using your API to become dependent on factors that may change as the structure of the objects does. Also try and keep the scope of your variables as low as possible. It is better to avoid global variables if you can in general. Passing them as parameters is almost always a better idea. Try to keep variables in the lowest scope possible.
Typically you would have your declarations inside a header file, and your definitions inside the cpp. There are many benefits to doing this, one of the biggest being re-usability. If you have multiple files that need to use a certain class, it is much easier to just include it where needed rather than having to re-declare it.
Being able to separate prototypes from the actual member bodies is also quite useful. This allows you to do things such as having a binary version of the implementation, and still keep the function names publicly available. This way if someone was using your class or library they could see how to use it, but not be able to see how it actually works. This is very important in larger projects and when copyright is involved.
This is a good habit to get into, but can get confusing and overwhelming if you don't stay organized. Common practice is to have an implementation file (.cpp) and a header (.h) for each class, both generally having the same name as the class to improve readability.
You should avoid using a header file just to declare local variables as it's generally best to keep them in the scope where they're needed.
As for your particular sample, you can avoid putting class private methods into the header file using the Pimpl Idiom. You'll have only publicly visible (public/protected) members declared in your header file, all the rest goes to the .cpp:
.h file:
class ClassA {
public:
ClassA();
~ClassA();
void foo();
private:
class ClassAImpl;
ClassAImpl* pImpl;
};
.cpp file:
#include "ClassA.h"
struct ClassAImpl
void function() {
// ...do something...
}
};
ClassA::ClassA()
: pImpl(new ClassAImpl()) {
}
ClassA::~ClassA() {
delete pImpl;
}
void ClassA::foo() {
pImpl->function();
}
Benefits of having a separate .h and .cpp file
Hide Implementation: You can separate the declaration from definition. So say you want to create an API, you could put your actual logic in .cpp (which becomes the library file on compilation) and have the declaration in .h which someone one could use to access the API.
Reduce Compilation time: One benefit of having definition in .cpp and declaration in .h is when you want to make changes to the definition. Such a change, would just change the cpp file and that .cpp will have to be recompiled. If the definition were to be in .h file, all the .cpp files where the .h file is included would have to be recompiled which would take more time.
Improves Readability: Having declaration and definition separate in some ways improves readability.
One of the reasons we have separate header and source files in C++ is because C++ code is unmanaged . It is directly executed by the processor (unlike C#, Java which are executed in a virtual environment). This requires having a header file to hold the symbol information which while being separate from the implementation, acts as an interface to it.
In C and C++, the order in which things are declared is important. Remember that when these languages were designed - compilers were not what they are today. Header files are things that you "include" which describe classes, type-definitions, enums. Now, you can provide implementation (and in the case of C++ template classes, you have to) in the header file. You put the implementation of the stuff in to the .cpp file. You're not writing a function twice (the compiler will have a hissy-fit if you do). You declare or implement them in the header file and then, in the case of the former, you implement them in the C++ file.
Consumers of your code (in a library project, for example), will include the header files (that describe the classes), and then link against an object file (as opposed to .cpp files). Header files provide you, ahead-of-time, the symbols to expect and link against.
Templates are a little weird in this respect (you don't export them), they are header file only (at the moment, I believe).
Modern languages such as C# do not have the concept of header files, because of the way the compiler works. The C# compiler looks at the files as a "whole" and therefore there is no need to forward declare anything or worry about header files. C/C++ compilers do not do this. I am unsure (without going and looking it up) whether or not this was due to compiler technology at the time or a concsious design decision at the time.
You are not duplicating code.
I have a theory question rather than an error report.
I'm a rookie C++ programmer, trying to promote that away
Using the VC++ VS2008 compiler
I am often finding myself wondering WHY I want to take some actions in header files.
For example look at this code block:
#include "DrawScene.h"
#include "Camera.h"
#include "Player.h"
#include "Grid.h"
#include "InputHandler.h"
#include "GameState.h"
class Controller
{
public:
private:
public:
Controller();
~Controller(){}
void Update();
private:
};
And the hooked up CPP file , controller.cpp along with it
#include "stdafx.h"
#include "glut.h"
#include "Controller.h"
#include <iostream>
Grid* grid_ptr = new Grid();
InputHandler* inputHandler_ptr = new InputHandler();
DrawScene* drawScene_ptr = new DrawScene();
GameState* gameState_ptr = new GameState();
Controller::Controller()
{
}
void Controller::Update()
{
}
What is a good way to decide which includes go where? So far I've been going with the " whatever works" method but I find it somewhat unprofessional.
Now even though you can say my code has X syntax errors and design flaws, please do, but the focal point I would appreciate that information remains on the use of .h VS .cpp files.
Why is there even such a design? And what are the pits and traps to always be treading lightly around when making any kind of OOP based C++ program?
What sparked this question for me btw was that I wanted to notify the reader of the header file there will be objects stored in the controller but assigning these uninitialized objects seemed impossible without making them static.
Note: I stem from C# --> C++ , might help to know. That's kind of my perspective on code at this point.
Thank you in advance for you efforts!
EDIT: 26/08/2010 18:16
So the build time is the essence of good includes. Is there more to be cautious about?
This is my personal opinion rather than a consensus best practice, but what I recommend is: in a header file, only include those headers that are necessary to make the contents of the header file compile without syntax errors. And if you can use forward declarations rather than nested inclusions, do so.
The reason for this is, in C++ (unlike C#, iiuc) there's no export control. Everything you include from a header will be visible to the includers of the header, which could be a whole lot of junk that users of your interface should not see.
Generally speaking headers should reside in the cpp file. For standard library includes (and possibly 3rd library includes) you can stick them in headers. However headers defined specifically for your project should go in cpp files whenever possible.
The reason for this is compilation time and dependency issues. Any time you change a header file, the compiler will have to recompile every source file that includes it. When you include a header file in another header file, then the compiler has to recompile every cpp file that includes either header file.
This is why forward declaration and the PIMPL (Pointer to IMPLementation, or opaque pointer) pattern are popular. It allows you to shift at least some of the changes/implementation out of the header file. For example:
// header file:
class SomeType;
class AnotherType
{
private:
SomeType *m_pimpl;
};
doesn't require you to include "sometype.h" whereas:
// header file
class AnotherType
{
private:
SomeType m_impl;
};
does. EDIT: Actually, you don't need to include "sometype.h" in the "anothertype.h" if you ALWAYS include "sometype.h" before "anothertype.h" in EVERY cpp file that includes "anothertype.h".
Sometimes it can be difficult to move a header file to the cpp file. At that point you have a decision - is it better to go through the effort of abstracting the code so you can do so, or is it better to just add the include?
Only include headers in another header if absolutely necessary. If the header can go solely in the source file then that's the best place. You can use forward declarations of classes in the header if you are only using pointers and references to them. Your DrawScene, GameState, Grid and InputHandler classes looks like they might fall into this category.
Note that C++ as a language does not care about the distinction between headers and source files. That's just an extremely common system used by developers to maintain their code. The obvious advantage of using headers is to avoid code duplication and helps, to an extent, to enforce the one-definition-rule for classes, templates and inline functions.
Avoid putting too many (read, any unnecessary) #includes in your .h file. Doing so can lead to long build times, as e.g. whenever you change Camera.h you will have changed Controller.h, so anything that includes Controller.h will need to be rebuilt. Even if it is only a comment that has changed.
Use forward declarations if you are only storing pointer members, then add the #includes to the cpp file.
Theoretically, .h files contain just the interface, and .cpp files, the implementation. However, since private members are arguably implementation, and not interface, this is not strictly true, hence the need for forward declarations in order to minimise unnecessary rebuilds.
It is possible, in C++, to include the whole implementation inline in the class definition, file, much as you might with Java, but this really breaks the .h/.cpp interface/implementation rule.
Header files contain declarations of functions, classes, and other objects, whereas cpp files are meant for implementing these previously declared objects.
Header files exist primarily for historical reasons. It's easier to build a C++ compiler if the definitions of all functions, classes, etc to be used by your code are given before you actually call them.
Usually you use cpp for your implemenation. Implementing functions in header files automatically inlines them, so unless these are very small and / or very frequently called, this is usually not what you want.
Should every .C or .cpp file should have a header (.h) file for it?
Suppose there are following C files :
Main.C
Func1.C
Func2.C
Func3.C
where main() is in Main.C file. Should there be four header files
Main.h
Func1.h
Func2.h
Func3.h
Or there should be only one header file for all .C files?
What is a better approach?
For a start, it would be unusual to have a main.h since there's usually nothing that needs to be exposed to the other compilation units at compile time. The main() function itself needs to be exposed for the linker or start-up code but they don't use header files.
You can have either one header file per C file or, more likely in my opinion, a header file for a related group of C files.
One example of that is if you have a BTree implementation and you've put add, delete, search and so on in their own C files to minimise recompilation when the code changes.
It doesn't really make sense in that case to have separate header files for each C file, as the header is the API. In other words, it's the view of the library as seen by the user. People who use your code generally care very little about how you've structured your source code, they just want to be able to write as little code as possible to use it.
Forcing them to include multiple distinct header files just so they can create, insert into, delete from, and search, a tree, is likely to have them questioning your sanity :-)
You would be better off with one btree.h file and a single btree.lib file containing all of the BTree object files that were built from the individual C files.
Another example can be found in the standard C headers.
We don't know for certain whether there are multiple C files for all the stdio.h functions (that's how I'd do it but it's not the only way) but, even if there were, they're treated as a unit in terms of the API.
You don't have to include stdio_printf.h, stdio_fgets.h and so on - there's a single stdio.h for the standard I/O part of the C runtime library.
Header files are not mandatory.
#include simply copy/paste whatever file included (including .c source files)
Commonly used in real life projects are global header files like config.h and constants.h that contains commonly used information such as compile-time flags and project wide constants.
A good design of a library API would be to expose an official interface with one set of header files and use an internal set of header files for implementation with all the details. This adds a nice extra layer of abstraction to a C library without adding unnecessary bloat.
Use common sense. C/C++ is not really for the ones without it.
I used to follow the "it depends" trend until I realized that consistency, uniformity and simplicity are more important than saving the effort to create a file, and that "standards are good even when they are bad".
What I mean is the following: a .cpp/.h pair of files is pretty much what all "modules" end up anyway. Making the existing of both a requirement saves a lot of confusion and bad engineering.
For instance, when I see some interface of something in a header file, I know exactly where to search for / place its implementation. Conversely, if I need to expose the interface of something that was previously hidden in .cpp file (e.g. static function becoming global), I know exactly where to put it.
I've seen too many bad consequences of not following this simple rule. Unnecessary inline functions, breaking any kind of rules about encapsulation, (non)separation of the interface and implementation, misplaced code, to name a few -- all due to the fact that the appropriate sibling header or cpp file was never added.
So: always define both .h and .c files. Make it a standard, follow it, and safely rely on it. Life is much simpler this way, and simplicity is the most important thing in software.
Generally it's best to have a header file for each .c file, containing the declarations for functions etc in the .c file that you want to expose. That way, another .c file can include the .h file for the functions it needs, and won't need to be recompiled if a header file it didn't include got changed.
Generally there will be one .h file for each .c/.cpp file.
Bjarne Stroustrup Explains it beautifully in his book "The C++ Programming Language"....
The single header style of physical partitioning is most useful when the program is small and its parts are not intended for separate use. When namespaces are used, the logical structure of the program can still be explained in a single header file.
For larger Programs, the single header file approach is unworkable in a conventional file-based development environment. A change to the common header forces recompilation of the whole program, and updates of that single header by several programmers are error prone. Unless strong emphasis is placed on programming styles relying heavily on namespaces and classes, the logical structure deteriorates as program grows.
An alternative physical organization lets each logical module have its own header defining the facilities it provides. Each .c file then has a corresponding h. file specifying what it provides(its interface). Each .c module includes its own .h file and usually also other .h files that specifies what it needs from other modules in order to implement the services advertised in its interface. This physical organization corresponds to the logical organization of a module. The multiple header approach makes it easy to determine the dependencies. The single header approach forces us to look at every declarations used by any module and decide if its relevant. The simple fact is that maintenance of a code is invariably done with incomplete information and from a local perspective.
The better localization leads to less information to compile a module and thus faster compilation..
It depends. Usually your reason for having separate .c files will dictate whether you need separate .h files.
Generally cpp/c files are for implementation and h/hpp (hpp are not used often) files are for header files (prototypes and declarations only). Cpp files don't always have to have a header file associated with it but it usually does as the header file acts like a bridge between cpp files so each cpp file can use code from another cpp file.
One thing that should be strongly enforced is the no use of code within a header file! There's been too many times where header files break compiles in any size project because of redefinitions. And that's simply when you include the header file in 2 different cpp files. Header files should always be designed to be included multiple times as well. Cpp files should never be included.
It's all about what code needs to be aware of what other code. You want to reduce the amount other files are aware of to the bare minimum for them to do their jobs.
They need to know that a function exists, what types they need to pass into it, and what types it will return, but not what it's doing internally. Note that it's also important from the programmers point of view to know what those types actually mean. (e.g which int is the row, and which is the column) but the code itself doesn't care. This is why naming the function and parameters sensibly is worthwhile.
As others have said, if there's nothing in a cpp file worth exposing to other parts of the code, as is normally the case with main.c, then there's no need for a header file.
It's occasionally worth putting everything you want to expose in a single header file (e.g, Func1and2and3.h), so that anything that knows about Func1 knows about Func2 as well, but I'm personally not keen on this, as it means that you tend to load a hell of a lot of junk along with the stuff you actually want.
Summary:
Imagine that you trust that someone can write code and that their algorithms, design, etc. are all good. You want to use code they've written. All you need to know is what to give them to get something to happen, what you should give it to, and what you'll get back. That's what needs to go in the header files.
I like putting interfaces into header files and implementation in cpp files. I don't like writing C++ where I need to add member variables and prototypes to the header and then the method again in the C++. I prefer something like:
module.h
struct IModuleInterface : public IUnknown
{
virtual void SomeMethod () = 0;
}
module.cpp
class ModuleImpl : public IModuleInterface,
public CObject // a common object to do the reference
// counting stuff for IUnknown (so we
// can stick this object in a smart
// pointer).
{
ModuleImpl () : m_MemberVariable (0)
{
}
int m_MemberVariable;
void SomeInternalMethod ()
{
// some internal code that doesn't need to be in the interface
}
void SomeMethod ()
{
// implementation for the method in the interface
}
// whatever else we need
};
I find this is a really clean way of separating implementation and interface.
There is no better approach, only common and less common cases.
The more common case is when you have a class/function interface to declare/define. It's better to have only one .cpp/.c with the definitions, and one header for the declarations.
Giving them the same name makes easy to understand that they are directly related.
But that's not a "rule", that's the common way and the most efficient in almost all cases.
Now in some cases( like template classes or some tiny struct definition ) you'll not need any .c/.cpp file, just the header. We often have some virtual class interface definition in only a header file for example, with only virtual pure functions or trivial functions.
And in other rare cases (like an hypothetical main.c/.cpp file) if wouldn't be always required to allow code from external compilation unit to call the function of a given compilation unit. The main function is an example (no header/declaration needed), but there are others, mostly when it's code that "connect all the other parts together" and is not called by other parts of the application. That's very rare but in this case a header make no sense.
If your file exposes an interface - that is, if it has functions which will be called from other files - then it should have a header file. Otherwise, it shouldn't.
As already noted, generally, there will be one header (.h) file for each source (.c or .cpp) file.
However, you should look at the cohesiveness of the files. If the various source files provide separate, individually reusable sets of functions - an ideal organization - then you should certainly have one header per file. If, however, the three source files provide a composite set of functions (that is too big to fit into one file), then you would use a more complex organization. There would be one header for the external services used by the main program - and that would be used by other programs needing the same services. There would also be a second header used by the cooperating source files that provides 'internal' definitions shared by those files.
(Also noted by Pax): The main program does not normally need its own header - no other source code should be using the services it provides; it uses the services provided by other files.
If you want your compiled code to be used from another compilation unit you will need the header files. There are some situations for which you do now need/want to have a headers.
The first such case are main.c/cpp files. This class is not meant to be included and as such there is no need for a header file.
In some cases you can have a header file that defines behavior of a set of different implementations that are loaded through a dll that is loaded at runtime. There will be different set of .c/.cpp files that implement variations of the same header. This can be common in plugin systems.
In general, I don't think there is any explicit relationship between .h and .c files. In many cases (probably most), a unit of code is a library of functionality with a public interface (.h) and an opaque implementation (.c). Sometimes a number of symbols are needed, like enums or macros, and you get a .h with no corresponding .c and in a few circumstances, you will have a lump of code with no public interface and no corresponding .h
in particular, there are a number of times when, for the sake of readability, the headers or implementations (seldom both) are so big and hairy that they end up being broken into many smaller files, for the sake of the programmer's sanity.
Should you declare the getters/setters of the class inside the .h file and then define them in .cpp Or do both in .h file. Which style do you prefer and why? I personally like the latter wherein all of them are in .h and only methods which have logic associated with it other than setters/getters in .cpp.
For me it depends on who's going to be using the .h file. If it's a file largely internal to a module, then I tend to put the tiny methods in the header. If it's a more external header file that presents a more fixed API, then I'll put everything in the .cpp files. In this case, I'll often use the PIMPL Idiom for a full compilation firewall.
The trade-offs I see with putting them in the headers are:
Less typing
Easier inlining for the compiler (although compilers can sometimes do inlining between multiple translation units now anyway.)
More compilation dependencies
I would say that header files should be about interface, not implementation. I'd put them in the .cpp.
For me this depends on what I'm doing with the code. For code that I want maintained and to last over time, I put everything in the .cc file for the following reasons:
The .h file can remain sparse as documentation for people who want to look for function and method definitions.
My group's coding guidelines state that we put everything in the .cpp file and like to follow those, even if the function definition only takes one line. This eliminates guessing games about where things actually live, because you know which file you should examine.
If you're doing frequent recompiles of a big project, keeping the function definition in the .cpp file saves you some time compared to keeping function definitions in header files. This was relevant very recently for us, as we recently went through the code and added a lot of runtime assert statements to validate input data for our classes, and that required a lot of modification to getters and setters. If these method declarations had lived in .cpp files, this would have turned into a clean recompile for us, which can take ~30min on my laptop.
That's not to say that I don't play fast-and-dirty with the rules occasionally and put things in .h files when implementing something really fast, but for code I'm serious about I all code (regardless of length) in the .cpp file. For big projects (some of) the rules are there for a reason, and following them can be a virtue.
Speaking of which, I just thought of yet another Perl script I can hack together to find violations of the coding guidelines. It's good to be popular. :)
I put put all single-liners in the header as long as they do not require too much additional headers included (because calling methods of other classes).
Also I do not try to put all code in one line so I can put most of the methods in the header :-)
But Josh mentioned a good reason to put them in the .cpp anyway: if the header is for external use.
I prefer to keep the .h file as clean as possible. Therefore, small functions that are as simple as get/set I often use to put in a separate file as inline-defined functions, and then include that file (where I use the extension .inl) into the .h header file:
// foo.h
class foo
{
public:
int bar() const;
private:
int m_bar;
};
#include "foo.inl"
// foo.inl
inline
int foo::bar() const
{
return m_bar;
}
I think that this gives the best of two worlds, at the same time hiding most of the implementation from the header, and still keep the advantage of inlining simple code (as a rule of thumb I keep it within at most 3 statements).
I pretty much always follow the division of declaring them in the header, and defining in the source. Every time I don't, I end up having to go back and do it any way later.
I prefer to put them into the .cpp file, for the sake of fast compile/link times. Even tiny one-liners (empty virtual destructors!) can blow up your compile times, if they are instantiated a lot. In one project, I could cut the compile time by a few seconds by moving all virtual destructors into the .cpp files.
Since then, I'm sold on this, and I would only put them into the header again if a profiler tells me that I can profit from inlining. Only downside is you need more typing, but if you create the .cpp file while you write the header, you can often just copy&paste the declarations and fill them out in the .cpp file, so it's not that bad. Worse of course if you later find out you want to move stuff into a .cpp file.
A nice side effect is that reading stuff is simpler when you have only documentation and declarations in your header, especially if new developers join the project.
I use next rule: header for declaration, code file for realization. It becomes for actual when your header would be use outside of project - than more lightweight your header is, then it's more comfort in use
My personal style with C++ has always to put class declarations in an include file, and definitions in a .cpp file, very much like stipulated in Loki's answer to C++ Header Files, Code Separation. Admittedly, part of the reason I like this style probably has to do with all the years I spent coding Modula-2 and Ada, both of which have a similar scheme with specification files and body files.
I have a coworker, much more knowledgeable in C++ than I, who is insisting that all C++ declarations should, where possible, include the definitions right there in the header file. He's not saying this is a valid alternate style, or even a slightly better style, but rather this is the new universally-accepted style that everyone is now using for C++.
I'm not as limber as I used to be, so I'm not really anxious to scrabble up onto this bandwagon of his until I see a few more people up there with him. So how common is this idiom really?
Just to give some structure to the answers: Is it now The Way™, very common, somewhat common, uncommon, or bug-out crazy?
Your coworker is wrong, the common way is and always has been to put code in .cpp files (or whatever extension you like) and declarations in headers.
There is occasionally some merit to putting code in the header, this can allow more clever inlining by the compiler. But at the same time, it can destroy your compile times since all code has to be processed every time it is included by the compiler.
Finally, it is often annoying to have circular object relationships (sometimes desired) when all the code is the headers.
Bottom line, you were right, he is wrong.
EDIT: I have been thinking about your question. There is one case where what he says is true. templates. Many newer "modern" libraries such as boost make heavy use of templates and often are "header only." However, this should only be done when dealing with templates as it is the only way to do it when dealing with them.
EDIT: Some people would like a little more clarification, here's some thoughts on the downsides to writing "header only" code:
If you search around, you will see quite a lot of people trying to find a way to reduce compile times when dealing with boost. For example: How to reduce compilation times with Boost Asio, which is seeing a 14s compile of a single 1K file with boost included. 14s may not seem to be "exploding", but it is certainly a lot longer than typical and can add up quite quickly when dealing with a large project. Header only libraries do affect compile times in a quite measurable way. We just tolerate it because boost is so useful.
Additionally, there are many things which cannot be done in headers only (even boost has libraries you need to link to for certain parts such as threads, filesystem, etc). A Primary example is that you cannot have simple global objects in header only libs (unless you resort to the abomination that is a singleton) as you will run into multiple definition errors. NOTE: C++17's inline variables will make this particular example doable in the future.
As a final point, when using boost as an example of header only code, a huge detail often gets missed.
Boost is library, not user level code. so it doesn't change that often. In user code, if you put everything in headers, every little change will cause you to have to recompile the entire project. That's a monumental waste of time (and is not the case for libraries that don't change from compile to compile). When you split things between header/source and better yet, use forward declarations to reduce includes, you can save hours of recompiling when added up across a day.
The day C++ coders agree on The Way, lambs will lie down with lions, Palestinians will embrace Israelis, and cats and dogs will be allowed to marry.
The separation between .h and .cpp files is mostly arbitrary at this point, a vestige of compiler optimizations long past. To my eye, declarations belong in the header and definitions belong in the implementation file. But, that's just habit, not religion.
Code in headers is generally a bad idea since it forces recompilation of all files that includes the header when you change the actual code rather than the declarations. It will also slow down compilation since you'll need to parse the code in every file that includes the header.
A reason to have code in header files is that it's generally needed for the keyword inline to work properly and when using templates that's being instanced in other cpp files.
What might be informing you coworker is a notion that most C++ code should be templated to allow for maximum usability. And if it's templated, then everything will need to be in a header file, so that client code can see it and instantiate it. If it's good enough for Boost and the STL, it's good enough for us.
I don't agree with this point of view, but it may be where it's coming from.
I think your co-worker is smart and you are also correct.
The useful things I found that putting everything into the headers is that:
No need for writing & sync headers and sources.
The structure is plain and no circular dependencies force the coder to make a "better" structure.
Portable, easy to embedded to a new project.
I do agree with the compiling time problem, but I think we should notice that:
The change of source file are very likely to change the header files which leads to the whole project be recompiled again.
Compiling speed is much faster than before. And if you have a project to be built with a long time and high frequency, it may indicates that your project design has flaws. Seperate the tasks into different projects and module can avoid this problem.
Lastly I just wanna support your co-worker, just in my personal view.
Often I'll put trivial member functions into the header file, to allow them to be inlined. But to put the entire body of code there, just to be consistent with templates? That's plain nuts.
Remember: A foolish consistency is the hobgoblin of little minds.
As Tuomas said, your header should be minimal. To be complete I will expand a bit.
I personally use 4 types of files in my C++ projects:
Public:
Forwarding header: in case of templates etc, this file get the forwarding declarations that will appear in the header.
Header: this file includes the forwarding header, if any, and declare everything that I wish to be public (and defines the classes...)
Private:
Private header: this file is a header reserved for implementation, it includes the header and declares the helper functions / structures (for Pimpl for example or predicates). Skip if unnecessary.
Source file: it includes the private header (or header if no private header) and defines everything (non-template...)
Furthermore, I couple this with another rule: Do not define what you can forward declare. Though of course I am reasonable there (using Pimpl everywhere is quite a hassle).
It means that I prefer a forward declaration over an #include directive in my headers whenever I can get away with them.
Finally, I also use a visibility rule: I limit the scopes of my symbols as much as possible so that they do not pollute the outer scopes.
Putting it altogether:
// example_fwd.hpp
// Here necessary to forward declare the template class,
// you don't want people to declare them in case you wish to add
// another template symbol (with a default) later on
class MyClass;
template <class T> class MyClassT;
// example.hpp
#include "project/example_fwd.hpp"
// Those can't really be skipped
#include <string>
#include <vector>
#include "project/pimpl.hpp"
// Those can be forward declared easily
#include "project/foo_fwd.hpp"
namespace project { class Bar; }
namespace project
{
class MyClass
{
public:
struct Color // Limiting scope of enum
{
enum type { Red, Orange, Green };
};
typedef Color::type Color_t;
public:
MyClass(); // because of pimpl, I need to define the constructor
private:
struct Impl;
pimpl<Impl> mImpl; // I won't describe pimpl here :p
};
template <class T> class MyClassT: public MyClass {};
} // namespace project
// example_impl.hpp (not visible to clients)
#include "project/example.hpp"
#include "project/bar.hpp"
template <class T> void check(MyClass<T> const& c) { }
// example.cpp
#include "example_impl.hpp"
// MyClass definition
The lifesaver here is that most of the times the forward header is useless: only necessary in case of typedef or template and so is the implementation header ;)
To add more fun you can add .ipp files which contain the template implementation (that is being included in .hpp), while .hpp contains the interface.
As apart from templatized code (depending on the project this can be majority or minority of files) there is normal code and here it is better to separate the declarations and definitions. Provide also forward-declarations where needed - this may have effect on the compilation time.
Generally, when writing a new class, I will put all the code in the class, so I don't have to look in another file for it.. After everything is working, I break the body of the methods out into the cpp file, leaving the prototypes in the hpp file.
I personally do this in my header files:
// class-declaration
// inline-method-declarations
I don't like mixing the code for the methods in with the class as I find it a pain to look things up quickly.
I would not put ALL of the methods in the header file. The compiler will (normally) not be able to inline virtual methods and will (likely) only inline small methods without loops (totally depends on the compiler).
Doing the methods in the class is valid... but from a readablilty point of view I don't like it. Putting the methods in the header does mean that, when possible, they will get inlined.
I think that it's absolutely absurd to put ALL of your function definitions into the header file. Why? Because the header file is used as the PUBLIC interface to your class. It's the outside of the "black box".
When you need to look at a class to reference how to use it, you should look at the header file. The header file should give a list of what it can do (commented to describe the details of how to use each function), and it should include a list of the member variables. It SHOULD NOT include HOW each individual function is implemented, because that's a boat load of unnecessary information and only clutters the header file.
If this new way is really The Way, we might have been running into different direction in our projects.
Because we try to avoid all unnecessary things in headers. That includes avoiding header cascade. Code in headers will propably need some other header to be included, which will need another header and so on. If we are forced to use templates, we try avoid littering headers with template stuff too much.
Also we use "opaque pointer"-pattern when applicable.
With these practices we can do faster builds than most of our peers. And yes... changing code or class members will not cause huge rebuilds.
I put all the implementation out of the class definition. I want to have the doxygen comments out of the class definition.
IMHO, He has merit ONLY if he's doing templates and/or metaprogramming. There's plenty of reasons already mentioned that you limit header files to just declarations. They're just that... headers. If you want to include code, you compile it as a library and link it up.
Doesn't that really depends on the complexity of the system, and the in-house conventions?
At the moment I am working on a neural network simulator that is incredibly complex, and the accepted style that I am expected to use is:
Class definitions in classname.h
Class code in classnameCode.h
executable code in classname.cpp
This splits up the user-built simulations from the developer-built base classes, and works best in the situation.
However, I'd be surprised to see people do this in, say, a graphics application, or any other application that's purpose is not to provide users with a code base.
Template code should be in headers only. Apart from that all definitions except inlines should be in .cpp. The best argument for this would be the std library implementations which follow the same rule. You would not disagree the std lib developers would be right regarding this.
I think your co-worker is right as long as he does not enter in the process to write executable code in the header.
The right balance, I think, is to follow the path indicated by GNAT Ada where the .ads file gives a perfectly adequate interface definition of the package for its users and for its childs.
By the way Ted, have you had a look on this forum to the recent question on the Ada binding to the CLIPS library you wrote several years ago and which is no more available (relevant Web pages are now closed). Even if made to an old Clips version, this binding could be a good start example for somebody willing to use the CLIPS inference engine within an Ada 2012 program.