views:

2966

answers:

14

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 Martin York'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?

+40  A: 

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 impossible 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.

Evan Teran
I'm pretty sure that's where he's getting it from. Whenver this comes up he brings up templates. His argument is roughly that you should do all code this way for consistency.
T.E.D.
that's a poor argument he's making, stick to your guns :)
Evan Teran
Template definitions can be in CPP files if the "export" keyword is supported. That's a dark corner of C++ that is usually not even implemented by most compiles, to the best of my knowledge.
Andrei Taranchenko
There is also explicit instantiation which lets you not have all the code in the header as well (only useful if you know all the possible instantiations you will need).
Evan Teran
See the bottom of this answer (the top is somewhat convoluted) for an example: http://stackoverflow.com/questions/555330/templates-use-forward-declarations-to-reduce-compile-time/555349#555349
Evan Teran
It starts being meaningful to this discussion at "Hooray, no linker errors."
Evan Teran
Given that my question boiled down to what the general consensus was, and this answer seems to have garnered the majority of all votes cast, and I have yet to se another contradict it, I'm accepting it.
T.E.D.
Even in template headers, it's a good idea to actually implement the code in another header and #include it at the bottom, just to separate stuff.
rlbond
A: 

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.

TofuBeer
+18  A: 

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.

Jekke
"The day C++ coders agree on The Way ... " there will only be one C++ coder left!
Brian Ensink
And it won't be me, because I can't always make up my mind.
David Thornley
I thought they already agree on the way, declarations in .h and definitions in .cpp
hasen j
+3  A: 

http://stackoverflow.com/questions/280033/c-header-files-code-separation

I would consider it uncommon from my experience this is the standard and shouldn't change IMHO.

Andrew Jahn
+10  A: 

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.

Laserallan
+2  A: 

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.

Virne
+5  A: 

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.

JohnMcG
I think you are right about this. When we discuss it he is always using the example of templates, where you more or less *have* to do this. I disagree with the "have to" as well, but my alternatives are rather convoluted.
T.E.D.
@ted - for templated code you do need to put the implementation in the header. The 'export' keyword allows a compiler to support separation of declaration and definition of templates, but support for export is prettymuch non-existant. http://anubis.dkuug.dk/jtc1/sc22/wg21/docs/papers/2003/n1426.pdf
Michael Burr
*A* header, yes, but it doesn't have to be the same header. See unknown's answer below.
T.E.D.
That makes sense, but I can't say I've come across that style before.
Michael Burr
+1  A: 

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.

Anonymous
That's what I took to doing with template definitions too (although I'm not sure I used the same extension...it's been a while).
T.E.D.
A: 

I put the all the implementation out of the class definition because I want to have the doxygen comments out of the class

xgoan
+5  A: 

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.

Mark Ransom
Yeah, I do that too. The general rule I use seems to be something along the lines of "if it fits on one line of code, leave it in the header".
T.E.D.
A: 

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.

EvilTeach
A: 

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.

spoulson
A: 

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.

Ed Woodcock
What exactly is the distinction between "Class code" and "Executable code"?
T.E.D.
As I said, it's a neural simulator: The user creates executable simulations which are built on a large number of classes that act as neurons etc.So our code is simply classes that cannot actually do anything by themselves, and the user creates the executable code that makes the simulator do stuff.
Ed Woodcock
Generally, couldn't you say "cannot actually do anything by itself" for the vast majority (if not the entirety) of most any program? Are you saying that the "main" code goes in a cpp, but nothing else does?
T.E.D.
In this situation it's a bit different.The code that we write is basically a library, and the user builds their simulations on top of this, which are actually runnable.Think about it like openGL -> you get a bunch of functions and objects but without a cpp file that can run them they're useless.
Ed Woodcock
+1  A: 

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 ;)

Matthieu M.