Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(C++) Whole class in .h file?

Tags:

c++

header

If I am creating a class with small functions that don't do much, is it acceptable to just put them all into the header file? So for a particular class, it's only just the .h with no .cpp to go with it.

like image 434
graydragon10 Avatar asked Sep 28 '10 07:09

graydragon10


People also ask

How do I include a class in a header file?

Traditionally, the class definition is put in a header file of the same name as the class, and the member functions defined outside of the class are put in a . cpp file of the same name as the class. Now any other header or code file that wants to use the Date class can simply #include "Date. h" .

What goes in a .h file C?

A header file is a file with extension . h which contains C function declarations and macro definitions to be shared between several source files. There are two types of header files: the files that the programmer writes and the files that comes with your compiler.

Can a header file have multiple classes?

There is no obligation regarding header and source files. In particular (contrarily to Java) you can (and often want) to have several declarations in a header file, and several class and function definitions (& implementation) in a source file.

Should each class have its own header file?

Each class shall have it's own header and implementation file. So if we wrote a class called MyString we would need an associated MyStringh. h and MyString.


1 Answers

Yes, that's acceptable. It will certainly compile. But also, if it makes the code organization cleaner, then that can be good. Most template definitions are already like this out of necessity, so you aren't doing anything unheard of. There can be some drawbacks of that class relies on other classes though. If you end up having to include the whole definition in other files that use the class, it may incur additional compile time compared to only having a brief class declaration.

You can measure your compilation times if this seems to be a real concern.

If you can get a copy, The c++ Programming Language (and many other books) have a detailed section about source code organization and the specific benefits of separating code into .h and .cpp files.

like image 176
JoshD Avatar answered Oct 06 '22 12:10

JoshD