where to put a class?

In general, should class appear in .h file (sort of like normal function prototype style) and then the .cpp file would #include the .h file OR should class just be directly defined in the .cpp file?

Just wondering, seen codes do either but which is better / recommended / preferred and why?


- mc0134

It's usually organized something like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
// Object.h ////////////////////////////////////////////////

class Object {
    int n;
public:
    Object();
    void inc();
    int get();
};


// Object.cpp //////////////////////////////////////////////

#include "Object.h"

Object::Object()
    : n(0)
{
}

void Object::inc() {
    ++n;
}

int Object::get() {
    return n;
}


// main.cpp ////////////////////////////////////////////////

#include <iostream>
#include "Object.h"

int main() {
    Object o;
    o.inc();
    o.inc();
    std::cout << o.get() << '\n';
}

You also can keep the class completely in the header file as many header-only libraries do.
In this case they are much easier to integrate in a project.
If you want to put the class in a.dll or .lib file you need to create a separate .cpp file.
If you don't need to show something to everyone, keep it to yourself.

So prefer to define your classes in the source file, where they won't pollute the rest of the program.
It's about interfaces: the header file should describe an interface that the source file (usually) implements and emphasize the structure of the program - i.e., the header files might logically segregate modules or sub-systems.

If the implementation of that interface uses some code internally, that internal code shouldn't be mentioned in the header file, because it's irrelevant to the interface the header is intended to describe. Indeed, names that aren't part of the interface should be given internal linkage, where possible.

There are also mechanical benefits. Additional code in header files:
- slows compilation of all the TUs (source files) which include the header
- introduces extra names into all of the TUs which include the header.
- makes the file harder to read

If you're writing templates, or you're trying to write a header-only library, you'll perhaps need to put the implementation in a header file, hopefully inside a details namespace.
Last edited on
Topic archived. No new replies allowed.