3

Possible Duplicate:
In C++ why have header files and cpp files?

I was wondering if it is advisable to write a the whole class c++ in a header file ? and use include to include the class, in a similar way that java does its oop programming. Is it a bad style ? can anyone recommend me a "good" C++ oop style guide ? Also I wondering if template programming is what they really mean when they talk about someone who is experienced in c++.

Community
  • 1
  • 1
George Host
  • 980
  • 1
  • 12
  • 26

3 Answers3

4

Including function definitions in a header file has some knock on effects and it's generally avoided. Functions defined in this manner are likely to be inlined, which will increase the size of your executable which can effect performance (in a positive or a negative way). Also, doing this can increase your build times, as having all definitions in line will increase the likelihood that you have to include additional files, etc.

The general practice is to put a classes interface in a header file (.h) and its implementation in a implementation file (.cpp).

In some cases it's required to have all of the code available -- as is the case with templates. The STL makes extensive use of templates and implementations of functions are included in the header files by necessity.

Chad
  • 18,706
  • 4
  • 46
  • 63
  • All correct. As a note, I've always preferred putting the template definitions below the class definition in a header, as recommended by http://www.parashift.com/c++-faq-lite/inline-functions.html#faq-9.7, so you still have the declaration/definiton seperation to some extent. – Mooing Duck Aug 15 '11 at 20:25
  • Yeah that makes more sense thanks ! – George Host Aug 15 '11 at 20:25
  • General practice according to whom? I.e., the vast majority of Boost is header-only -- does that not count? – ildjarn Aug 15 '11 at 20:43
  • @Mooing I'd even use extra .inl files (included in the header) for the definitions. – Christian Rau Aug 15 '11 at 22:06
1

Put public class and functions declaration in .h Put definitions and everything else in .cpp

.h is your interface, .cpp is your implementation.

nulvinge
  • 1,600
  • 8
  • 17
0

It's always better style to separate the declaration from the implementation, especially for more complicated functions.

Templates are something a little bit more advanced.

A good primer is: http://www.cplusplus.com/doc/tutorial/classes/

Mike D
  • 4,938
  • 6
  • 43
  • 99