0

Comming from a mostly Java background I recently started learning a bit of C++. I'm trying to create a class that describes a LinkedList. Since I want this class to be something like an external library, so I can use it in other applications, I need it to be declared as a header file.

I understand that from a design point of view C++ needs both a header and a cpp file, where the header will mostly contain declarations and the implementation will be left for the cpp file.

What I don't understand though is what is the actual purpose of the above design technique. The point of being able to quickly go through the header file and read the comments about the functionality of each method seems moot to me, since C++ (or at least my Codeblocks editor) supports the /** comments like Java so it is much easier to create an object of the class and simply hit the . button to open the methods description menu, and read any description I like in a more orderly and structured manner than going through a header file.

Also I noticed that the program runs fine if put everything inside the header file and completly ignore the cpp file.

So my question boils down to whether I should just implement everything in the header file, or whether this is considered unacceptable C++ coding practice and if so, why.

apboutos
  • 109
  • 2
  • 16
  • I'm not asking the exactly same thing. – apboutos Jul 02 '16 at 09:01
  • 1
    A lot of C++ library are actually implemented as "header only" (most of boost, for instance). So yeah, go ahead. The only pitfall is that you can't instanciate global variables in a header, you can only reference them. – kebs Jul 02 '16 at 09:05
  • 1
    It's not so much a matter of asking the exactly same question, but the existing answers are good enough to answer what you're asking here. – πάντα ῥεῖ Jul 02 '16 at 09:05
  • 1
    Agree with @πάντα ῥεῖ , the erased comment link ( http://stackoverflow.com/questions/583255/ ) covers the topic pretty well, and makes some good points: putting implementation in cpp files has some advantages on build time. – kebs Jul 02 '16 at 09:08
  • Thanks for the link it clarifies the point I'm asking a lot – apboutos Jul 02 '16 at 09:22

1 Answers1

0

Headers contain the bare minimum required to be able to use the functionality, since they get to some intermediate preprocessed file. The smaller that file, the easier to compile that unit.

They have to contain structure definitions and function declaration in this sense. This is unlike Java which doesn't require prior declaration in order to use and is a historical artifact which cannot be fixed now. The #include lines really paste the text in the header within the actual C/CPP file (sort of -- the preprocessing, conditional compilation etc have to happen in the headers too)

Paul Stelian
  • 1,381
  • 9
  • 27